实现Activity中使用 PopupWindow 使点击区域外不消失方案:
第一步:属性设置:
(1)通过
setFocusable(boolean focusable)设置当前的PopupWindow是否获取焦点:true-获取焦点;
(2)通过
setOutsideTouchable(boolean touchable)设置
点击当前的popupWindow区域外的touch事件是否有效;(默认为false)
只有当setFocusable设置false的条件下,touchable为true时,setOutsideTouchable为false才有效。
(实质:pop不消费事件,传递给宿主activity中的其他view控件)
[源码]
/**
* <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;
}
第二步:重写Activity中dispatchTouchEvent方法:
当设置popupWindow的setFocusable( false ),设置setOutsideTouchable ( false ) 时
popupWindow是不会dismiss的
,但是
区域外的点击事件已经传递到popupwindow下面的activity了,点击activity下面的控件会有作用的
。这就坑爹了,点击区域外不消失的效果是做到了,可是点击区域外,也就是popupWindow下面的activity的控件例如button时会响应onClickListener的。那该怎么使activity不分发popupWindow区域外的点击事件呢?
Android中的事件分发机制
activity中有两个重要的处理事件的方法dispatchTouchEvent和onTouchEvent。在这里主要是利用了
dispatchTouchEvent。
dispatchTouchEvent负责事件的分发,调用super.dispatchTouchEvent才会往下如ViewGroup传递事件。Activity中当dispatchTouchEvent返回false或者true时:事件停止传递,没继续往下传递,事件被消费了。
那我们就重写activity中
dispatchTouchEvent
,在里面判断popupWindow是否显示来决定是否往下分发事件。
@Override
public
boolean
dispatchTouchEvent
(MotionEvent event){
if
(mPopupWindow!=
null
&&mPopupWindow.isShowing()){
return
false
;
//源码建议返回true表示自身消费这个事件,不传递给子view,这里测试过返回true-false都可以
}
return
super
.dispatchTouchEvent(event); }
popupWindow的设置:
mPopupWindow=new PopupWindow(selectView, ViewGroup
.LayoutParams.MATCH
_PARENT, ViewGroup
.LayoutParams.WRAP
_CONTENT,true)
;
mPopupWindow
.setFocusable
(false)
;
mPopupWindow
.setOutsideTouchable
(false)
;
mPopupWindow
.showAtLocation
(findViewById(R
.id.EditActivity
_rootView), Gravity
.BOTTOM
,
0
,
0
)
;
OK,大功告成。
至于PopupWindow结合fragment使用时该方案是否有效,暂未测试过。