如何关闭弹出 window onClick of button 和 onTouch of outside in android

How to close popup window onClick of button and onTouch of outside in android

我试过如下

popupMoreWindow.setBackgroundDrawable(new BitmapDrawable());
popupMoreWindow.setOutsideTouchable(true);

if(popupOpened) {
    popupMoreWindow.dismiss();
    popupOpened = false;
} else {
    popupMoreWindow.showAsDropDown(custLookUpRowowHolder.btnMore, 150, 5);
    popupOpened = true;
}
  • 要在单击按钮和单击外部时关闭弹出窗口 window,请按照以下步骤操作

    1. 触摸拦截器并在动作为 MotionEvent 时关闭弹出窗口。 ACTION_OUTSIDE 使用 setFocusable(true)

    2. 将弹出窗口设置为可聚焦
    3. 设置 focusable 可确保弹出窗口可以抓取外部触摸事件,并且由于它还会捕获对菜单项或按钮的点击,因此它确保弹出窗口在已经显示时不会再次启动。

    4. 满足您要求的代码片段应如下所示。


btn.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {

    @Override
    public boolean onMenuItemClick(MenuItem item) {         

        if (window == null) {
            View contentView = getLayoutInflater(null).inflate(R.layout.popup_menu, null);
            window = new PopupWindow(contentView, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
            window.setBackgroundDrawable(new BitmapDrawable(getResources(), ""));               

            window.setOutsideTouchable(true);
            window.setFocusable(true);
            window.setTouchInterceptor(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if(event.getAction()==MotionEvent.ACTION_OUTSIDE){
                        window.dismiss();
                        return true;
                    }
                    return false;
                }
            });
        }           

        window.showAsDropDown(getActivity().findViewById(R.id.action_open_popup));
        return true;
    }
});

`