MauroAlexandro MauroAlexandro - 3 months ago 129
Android Question

Dim the background using PopupWindow in Android

Can I dim the background using a PopupWindow instead of a Dialog? I am asking this because I am using Dialogs but the Dialog doesn't show below the item clicked and with the PopupWindow I already have the popup showing below the item.

Answer

I use following code,and it works well to me.

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

From This answer .