Search code examples
androidpopupwindow

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


I tried like below

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

if(popupOpened) {
    popupMoreWindow.dismiss();
    popupOpened = false;
} else {
    popupMoreWindow.showAsDropDown(custLookUpRowowHolder.btnMore, 150, 5);
    popupOpened = true;
}
  • It was closing popup window, but not working for button onClick.

Solution

    • To close the popup window on click of button and on click of outside, follow as below

      1. The touch interceptor and dismiss the popup when action is MotionEvent. ACTION_OUTSIDE Set the popup to be focusable using setFocusable(true)

      2. Setting focusable ensures that popup can grab outside touch events and since it will also capture the click on the menuitem or a button, It ensures that popup is not launched again if it is already showing.

      3. And code snippet that fullfills ur requirement should be as below.


    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;
        }
    });
    
    `