android PopupWindow 点击外部,让pop消失,但是并不响应外部 view

关于popupWindow的细节:请看这个链接:从源码剖析PopupWindow 兼容Android 6.0以上版本点击外部不消失

// 我的代码
// findLayout(); 是一个自定义的方法,返回一个 xml 中的 布局
final LinearLayout va = findLayout();
        if (mPopupWindow == null) {
            mPopupWindow = new PopupWindow(va.getContext());
        }
        mPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mPopupWindow.setHeight(FrameLayout.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setContentView(va);
        // 设置PopupWindow的背景
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        // 设置PopupWindow是否能响应外部点击事件
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true); // pop 显示时, 不让外部 view 响应点击事件

        if (mPopupWindow.getContentView() != null) {
            mPopupWindow.getContentView().setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        hidePopupWindow();
                        if (cancelListener != null) {
                            cancelListener.cancel(v);
                        }
                        return true;
                    }
                    return false;
                }
            });
        }
        // 添加动画
        if (animationStyle > 0) {
            mPopupWindow.setAnimationStyle(animationStyle);
        }
        // 底部被导航栏遮挡问题解决
        mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        // window.showAsDropDown(v);
        // 设置popupWindow的显示位置,此处是在手机屏幕底部且水平居中的位置
        mPopupWindow.showAtLocation(button, Gravity.BOTTOM
                | Gravity.CENTER_HORIZONTAL, 0, 0);

核心代码:

// 设置PopupWindow的背景
mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// 设置PopupWindow是否能响应外部点击事件
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.setTouchable(true);
mPopupWindow.setFocusable(true); // pop 显示时, 不让外部 view 响应点击事件

这4句放一块,就能做到,点击外部 view 的时候, pop 消失,并且外部 view 不被响应。

如果要pop 消失,同时外部 view 被响应的话,就去掉mPopupWindow.setFocusable(true);这一句。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值