PopupWindow和dialog的实战与区别讲解

本文详细介绍了PopupWindow和Dialog在Android开发中的应用,包括它们的封装、显示位置、宽高设置、返回键监听、蒙层处理、点击关闭行为以及阻塞特性。此外,还探讨了在不同场景下如何选择使用Dialog或PopupWindow。
摘要由CSDN通过智能技术生成

前言:

dialog和PopupWindow在开发中是比较常用的两个View,二者都需要在Window上显示出来,正所谓有view的地方就有window,同时二者都需要调用setContentView方法,为什么请查看文章(Activity Window View三者之间的关系 https://blog.csdn.net/xgangzai/article/details/81390630)。

封装的dialog

dialog采用构造者模式,同属包括内部某按钮点击事件的接口回调,以及EditText等控件输入后在Activity中值的获取等。

  • 自定义dialog
public class CustomDialog extends Dialog {
   
    private Context context;
    private int height, width;
    private boolean cancelTouchOut;
    private View view;

    private CustomDialog(Builder builder) {
        super(builder.context);
        context = builder.context;
        height = builder.height;
        width = builder.width;
        cancelTouchOut = builder.cancelTouchOut;
        view = builder.view;
    }

    private CustomDialog(Builder builder, int resStyle) {
        super(builder.context, resStyle);
        context = builder.context;
        height = builder.height;
        width = builder.width;
        cancelTouchOut = builder.cancelTouchOut;
        view = builder.view;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(view);
        setCanceledOnTouchOutside(cancelTouchOut);
        Window win = getWindow();
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.height = height;
        lp.width = width;
        win.setAttributes(lp);
    }

    public static final class Builder {
   
        private Context context;
        private int height, width;
        private boolean cancelTouchOut;
        private View view;
        private int resStyle = -1;

        public Builder(Context context) {
            this.context = context;
        }

        public Builder view(int resView) {
            view = LayoutInflater.from(context).inflate(resView, null);
            return this;
        }

        public Builder heightpx(int val) {
            height = val;
            return this;
        }

        public Builder widthpx(int val) {
            width = val;
            return this;
        }

        public Builder heightdp(int val) {
            height = DensityUtil.dip2px(context, val);
            return this;
        }

        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值