PopupWindow实现弹窗,可以任意自定义布局

用于实现弹窗,可以任意自定义布局,android中弹窗可以分为AlertDialog和popupWindow,AlertDialog只能显示固定在中间位置,popupWindow可以在任意位置,相对更加灵活。

1.主布局设置

2.自定义弹窗布局

3.代码实现
//为弹窗提供自定义的布局
//创建弹窗PopupWindow
//设置相关的属性
//显示弹窗

private View button_update;
    private View button_delete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    //点击button事件
    public void submitClick(View view){
        showSubmitClick(view);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void showSubmitClick(View view) {  View v=getLayoutInflater().inflate(R.layout.popup_window,null);  //加载的布局
        button_update = v.findViewById(R.id.button_update);
        button_delete = v.findViewById(R.id.button_delete);

//创建弹窗popupwindow
        PopupWindow popupWindow =new PopupWindow(v, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,true);

 //设置背景      popupWindow.setBackgroundDrawable(getDrawable(R.mipmap.index_intro_bg));
        BitmapDrawable bitmapDrawable =new BitmapDrawable(getResources(),
                BitmapFactory.decodeResource(getResources(),R.mipmap.index_intro_bg));
        //设置透明度
        popupWindow.getBackground().setAlpha(80);
        //设置动画效果      popupWindow.setAnimationStyle(android.R.anim.fade_in);
        //设置点击弹窗外面消失
        popupWindow.setOutsideTouchable(true);
        //设置防止软键盘遮挡popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MODE_CHANGED);
        //显示弹窗
        popupWindow.showAsDropDown(view);
        //设置点击事件
        button_delete.setOnClickListener(this);
        button_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
    }

你可能感兴趣的:(popup弹窗)