版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DucklikeJAVA/article/details/82384576
关于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);
这一句。