在Android中使用PopupWindow调暗背景

Mau*_*dro 5 android dialog popupwindow android-dialog android-popupwindow

我可以使用PopupWindow而不是Dialog来调暗背景吗?我问这个是因为我正在使用Dialogs,但Dialog没有显示在点击的项目下面,并且PopupWindow我已经在项目下面显示了弹出窗口.

Jia*_*aGu 23

我使用以下代码,它对我很有用.

public static void dimBehind(PopupWindow popupWindow) {
    View container;
    if (popupWindow.getBackground() == null) {
        if (VERSION.SDK_INT >= VERSION_CODES.M){
            container = (View) popupWindow.getContentView().getParent();
        } else {
            container = popupWindow.getContentView();
        }
    } else {
        if (VERSION.SDK_INT >= VERSION_CODES.M) {
            container = (View) popupWindow.getContentView().getParent().getParent();
        } else {
            container = (View) popupWindow.getContentView().getParent();
        }
    }
    Context context = popupWindow.getContentView().getContext();
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams();
    p.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
    p.dimAmount = 0.3f;
    wm.updateViewLayout(container, p);
}
Run Code Online (Sandbox Code Playgroud)

这个答案.

更新:

下面的fdermishin的答案更好.我已经测试了它向API级别19,它运作良好.

如果您使用kotlin,最好将其用作kotlin扩展:

//Just new a kotlin file(e.g. ComponmentExts),
//copy the following function declaration into it
/**
 * Dim the background when PopupWindow shows
 */
fun PopupWindow.dimBehind() {
    val container = contentView.rootView
    val context = contentView.context
    val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val p = container.layoutParams as WindowManager.LayoutParams
    p.flags = p.flags or WindowManager.LayoutParams.FLAG_DIM_BEHIND
    p.dimAmount = 0.3f
    wm.updateViewLayout(container, p)
}

//then use it in other place like this?
popupWindow.dimBehind()
Run Code Online (Sandbox Code Playgroud)

  • View container =(View)popUp.getContentView().getRootView(); 这适用于前后M.在果冻豆和棉花糖中检查. (2认同)

fde*_*hin 14

似乎我想出了如何摆脱API版本检查.使用container = popupWindow.getContentView().getRootView()解决了问题,但我还没有测试它的旧API.适应Junyue Cao的解决方案:

public static void dimBehind(PopupWindow popupWindow) {
    View container = popupWindow.getContentView().getRootView();
    Context context = popupWindow.getContentView().getContext();
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams();
    p.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
    p.dimAmount = 0.3f;
    wm.updateViewLayout(container, p);
}
Run Code Online (Sandbox Code Playgroud)

  • 在 API 级别 21 和今天最新的 (28) 上进行了测试,它适用于所有版本。 (2认同)