Reputation: 26427
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)
Upvotes: 3
Views: 1402
Reputation: 61009
I see PopupMenu
close when you touch outside and when you click on back button. Therefore, to make PopupWindow
can dismiss like PopupMenu
you should use
popupWindow.isFocusable = true
// or you can send focusable when initialize PopupWindow because they have constructor like PopupWindow(View contentView, int width, int height, boolean focusable)
You can check my full answer here to know why we should use isFocusable
.
Upvotes: 0
Reputation: 3699
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);
Upvotes: 4
Reputation: 8844
// To close the popup window when touch outside.
mPopupWindow.setOutsideTouchable(true);
// Set focusable to popup window so that when touch it could dismiss the window
mPopupWindow.setFocusable(true);
// if you want to remove the default background.
mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
setOutsideTouchable(boolean touchable) Controls whether the pop-up will be informed of touch events outside of its window.
setFocusable(boolean focusable) Changes the focusability of the popup window.
setBackgroundDrawable(Drawable background) Specifies the background drawable for this popup window.
Upvotes: 1