通过在外部单击可以关闭 PopupMenu 的方式关闭 PopupWindow

Dismissing PopupWindow the way PopupMenu can be dismissed by clicking outside

我开发了一个 Android 平板电脑应用程序。当用户单击设置按钮时,我想在屏幕右上角向用户显示一个对话框,可以在其中配置设置。

鉴于对话框很复杂,我觉得 PopupWindowPopupMenu 更合适。 PopupMenu 具有良好的行为,当用户在菜单外单击时它会自动关闭。如何让 PopupWindow 以同样的方式运行?

            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)

我看到 PopupMenu 在您触摸外部和单击后退按钮时关闭。因此,要使 PopupWindow 可以像 PopupMenu 一样解散,您应该使用

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) 

你可以在这里查看 my full answer 以了解我们为什么要使用 isFocusable

// 触摸外部时关闭弹出窗口window。

mPopupWindow.setOutsideTouchable(true);

// 将 focusable 设置为弹出 window 以便在触摸时可以关闭 window

mPopupWindow.setFocusable(true);

// 如果要删除默认背景。

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.

您只需要设置 PopupWindowsetBackgroundDrawablesetOutsideTouchable 属性,如果您触摸它的外部,它应该关闭 window。

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