PopupWindow 无法在点击外部后自动消失的问题
Author: nex3z
2017-02-06
最近在 Android 5.x 上遇到了一个 PopupWindow 无法消失的问题,PopupWindow 已经设置了
popup.setOutsideTouchable(true);
但点击 PopupWindow 外部无法消除 PopupWindow。在 Android 6.0 上没有此问题。
该问题的原因是在使用PopupWindow时,为了取消默认的带阴影效果,使用了
popup.setBackgroundDrawable(null);
使用非 null 的 Background 即可解决此问题,如:
popup.setBackgroundDrawable(
new ColorDrawable(ContextCompat.getColor(this, R.color.popupBackground)));
查看 Android 5.1 版本中的 PopupWindow 可以看到,在 preparePopup() 阶段,会检查 mBackground 是否为 null,若不为 null,则会生成一个 PopupViewContainer:
private void preparePopup(WindowManager.LayoutParams p) {
// ...
if (mBackground != null) {
// ...
// when a background is available, we embed the content view
// within another view that