Search code examples
androidandroid-popupwindow

Dismissing PopupWindow the way PopupMenu can be dismissed by clicking outside


I develop an Android App for tablets. When the user clicks on a setting button I want to show the user a dialog on the upper right side of the screen where the settings can be configured.

Given that the dialog is complex I feel like PopupWindow is more appropriate then PopupMenu. PopupMenu has the nice behavior that it dismisses automatically when the user clicks outside of the menu. How do I get PopupWindow to behave the same way?

            val popupView = layoutInflater.inflate(R.layout.popup_window, null)
            val popupWindow = PopupWindow(
                popupView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            popupWindow.showAsDropDown(appCompactImageButton, 20, 0)

Solution

  • You just need to set setBackgroundDrawable and setOutsideTouchable properties of PopupWindow it should close the window if you touch outside of it.

    PopupWindow popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    popupWindow.setBackgroundDrawable(new ColorDrawable());
    popupWindow.setOutsideTouchable(true);