Android之解决点击PopupWindow外部不消失并且不穿透事件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011068702/article/details/81370161

1 问题

需要实现PopupWindow内部可以点击,但是外部点击不会消失

2 初步解决办法

设置PopupWindow的mFocusable属性mOutsideTouchable属性,我们知道如果我们不想穿透事件,也就是说,不想出现点击Popuowindow外部的文本框或者按钮生效,我们需要获取Popuowindow的焦点,也就是设置mFocusable值为true

也就是setFocusable( true ),然后我们分析mOutsideTouchable的设置函数解释

    /**
     * <p>Controls whether the pop-up will be informed of touch events outside
     * of its window.  This only makes sense for pop-ups that are touchable
     * but not focusable, which means touches outside of the window will
     * be delivered to the window behind.  The default is false.</p>
     *
     * <p>If the popup is showing, calling this method will take effect only
     * the next time the popup is shown or through a manual call to one of
     * the {@link #update()} methods.</p>
     *
     * @param touchable true if the popup should receive outside
     * touch events, false otherwise
     *
     * @see #isOutsideTouchable()
     * @see #isShowing()
     * @see #update()
     */
    public void setOutsideTouchable(boolean touchable) {
        mOutsideTouchable = touchable;
    }

里面很关键的一句,popuoWindow需要可触摸而且不能聚焦,特么刚才不是说要聚焦popupWindow吗?矛盾了

setFocusable(true)
setOutsideTouchable(false)

这样写聚焦了,外部点击会导致PopuoWindow消失,因为setOutsideTouchable没生效,虽然事件不穿透,点击外部消失PopupWindow,依然不是我想要的效果,所以就改成了这样

setFocusable(false)
setOutsideTouchable(false)

3 依然存在的问题

按照上面的修改,虽然点击外部PopupWindow不消失了,但是特么可以点击外部的EditView,特么我不想出现这样的效果,希望点击外部没反应,还有其它办法吗?

4 分析

既然涉及到了点击,事件分发,我们需要自然而然想到事件分发

既点击外部的PopupWindow的时候,我们让事件不分发进去就行,我们知道

Activity事件分发有2种形式,dispatchTouchEvent 方法onTouchEvent方法

我们这里重写dispatchTouchEvent方法,在出现Popupwindow的时候,返回false就行了,点击无效

5 实现

    //为了解决弹出PopupWindow后外部的事件不会分发,既外部的界面不可以点击
    @Override
    public boolean dispatchTouchEvent(MotionEvent event){
        if (popupWindow != null && popupWindow.isShowing()){
            return false;
        return super.dispatchTouchEvent(event);
    }

6 总结

只要我们想要实现点击一些东西,我们需要想到Activity的事件分发,让事件不要分下去,也就点击无效了,我们需要自然而然想到Activity的dispatchTouchEvent和onTouchEvnet方法

猜你喜欢

转载自blog.csdn.net/u011068702/article/details/81370161