如果出现第一次点击Button会显示,再次点击就消失不了的问题(因为按下的时候popupWindo会先消失,但是抬起来又会显示)
(核心 就是设置popupWindo的点击事件拦截监听,这里判断了是否点击到popupWindo的外面并且在指定的控件上面 )
解决方案: 直接来代码,
public class MainActivity extends AppCompatActivity {
private MePopupWindow popupWindow ;
private View btn ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R .layout .activity_main );
findViewById(R .id .btn ).setOnClickListener(new View .OnClickListener () {
@Override
public void onClick (View v) {
showAndDismissPop();
}
});
}
/**
* 显示 pop/ 隐藏 pop
*/
public void showAndDismissPop () {
// 隐藏 pop
if (popupWindow != null && popupWindow .isShowing()) {
popupWindow .dismiss();
return ;
}
// 显示 pop
if (popupWindow == null ) {// 创建新的
createPopupWindow(popupWindow = new MePopupWindow(this ));
} else if (!popupWindow .isShowing()) {// 复用老的
popupWindow .showAsDropDown(btn );
}
}
/**
* 创建新的窗体并显示
*/
public void createPopupWindow (MePopupWindow popupWindow) {
View root = View .inflate (this , R .layout .pop_filtrate , null );
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setOutsideTouchable(true );// 这个是点击外部消失
popupWindow.setContentView(root);
setPopTouchInterceptor();
popupWindow.setWidth(FrameLayout .LayoutParams .MATCH_PARENT );
popupWindow.setHeight(FrameLayout .LayoutParams .WRAP_CONTENT );
popupWindow.showAsDropDown(btn );
}
/**
* 设置 Pop 点击事件拦截监听
*/
public void setPopTouchInterceptor () {
popupWindow .setTouchInterceptor(new View .OnTouchListener () {
@Override
public boolean onTouch (View v, MotionEvent event) {
popupWindow .dismiss();
// 如果焦点不在 popupWindow 上
if (event.getAction() == MotionEvent .ACTION_OUTSIDE && !popupWindow .isFocusable()) {
// 并且点击到了 Button 上面 , 那么返回 true, 不做 dismiss 的操作 , 反之返回 false
return isInChangeImageZone(btn , (int ) event.getRawX(), (int ) event.getRawY());
}
return false ;
}
});
}
private Rect mChangeImageBackgroundRect = null ;
/**
* 判断是否点击到了指定的控件上面
*/
private boolean isInChangeImageZone (View view, int x, int y) {
if (null == mChangeImageBackgroundRect ) {
mChangeImageBackgroundRect = new Rect();
}
view.getDrawingRect(mChangeImageBackgroundRect );
int [] location = new int [2 ];
view.getLocationOnScreen(location);
mChangeImageBackgroundRect .left = location[0 ];
mChangeImageBackgroundRect .top = location[1 ];
mChangeImageBackgroundRect .right = mChangeImageBackgroundRect .right + location[0 ];
mChangeImageBackgroundRect .bottom = mChangeImageBackgroundRect .bottom + location[1 ];
return mChangeImageBackgroundRect .contains(x, y);
}