PopupWindow中使用GridView

来源:互联网 发布:qq和微信 知乎 编辑:程序博客网 时间:2024/05/22 14:12

PopupWindow中使用GridView

PopupWindow的一般使用方法大家都知道:

mPopupWindow = new PopupWindow();mPopupWindow.setBackgroundDrawable(new BitmapDrawable());mPopupWindow.setOutsideTouchable(true);mPopupWindow.setFocusable(true);mPopupWindow.showAsDropDown(anchor);

这样写的效果就是当mPopupWindow显示的时候,随便点击mPopupWindow以外的区域,mPopupWindow都会消失。(实际测试 mPopupWindow.setOutsideTouchable(true)并没有什么卵用,不写也一样)

但项目中遇到个问题,当点击Btn1的时候,mPopupWindow显示,点击btn2的时候,mPopupWindow不要消失,而是更换mPopupWindow中的contentView(dismiss后再show也是可以)。但是这种写法无论如何也没法做到。

尝试去掉mPopupWindow.setFocusable(true),开始看似很完美的解决了问题,但是有个contentview中用到了GridView,出问题了,gridview中的item死活接受不到ontouch事件,看来mPopupWindow如果无法获得焦点,touch事件也无法传递给gridview…

经过一番搜索,终于找到解决方法,利用java的反射机制:

/**     * Set whether this window is touch modal or if outside touches will be sent     * to     * other windows behind it.     *     */    public static void setPopupWindowTouchModal(PopupWindow popupWindow,            boolean touchModal) {        if (null == popupWindow) {            return;        }        Method method;        try {            method = PopupWindow.class.getDeclaredMethod("setTouchModal",                    boolean.class);            method.setAccessible(true);            method.invoke(popupWindow, touchModal);        }        catch (Exception e) {            e.printStackTrace();        }    }

原来想让mPopupWindow不消失,事件又向下传递,需要给Window设置一个Flag:
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
这个Flag的设置与否是由一个叫mNotTouchModal的字段控制,但是设置该字段的set方法被标记为@hide,所以要通过反射的方法调用。

参考:http://www.cnblogs.com/mengdd/p/3569127.html

0 1
原创粉丝点击