关于 PopupWindow 响应 Back 按键收起

项目中遇到一个Bug:PopupWindow 不响应 Back 键收回了。

google了一下,发现解决方法是:PopupWindow#setBackgroundDrawable(new BitmapDrawable())

具体原因是:

The reason the background cannot be null is because of what happens in PopupWindow#preparePopup. If it detects background != null it creates an instance of PopupViewContainer and calls setBackgroundDrawable on that and puts your content view in it. PopupViewContainer is basically a FrameLayout that listens for touch events and the KeyEvent.KEYCODE_BACK event to dismiss the window. If background == null, it doesn't do any of that and just uses your content view. You can, as an alternative to depending on PopupWindow to handle that, extend your root ViewGroup to behave the way you want.

翻译一下就是:在 PopupWindow 初始化的时候会监测是否设置了背景。如果已设置的话,会创建一个 PopupViewContainer (类似于 FrameLayout)来监听 Back 按键。但如果没有设置背景,就不会创建 PopupViewContainer,因此无监听。当然,也可以利用 PopupWindow 的 root ViewGroup 来处理监听。

posted @ 2016-07-15 13:52  NoodleUtopia  阅读(306)  评论(0编辑  收藏  举报