Blur or Dim Background When Android Popupwindow Active

Dim the background using PopupWindow in Android

I use the following code, and it works well for 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.

Update:

The fdermishin's answer below is better. I have tested it backwards to API level 19 and it works well.

If you are using Kotlin, it is better to use it as Kotlin extension:

//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()

Dim or blur background of popup window

You can do it in 2 ways

1. by adding background color with transparency, to the parent of your popup layout.
example:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#cc000000">

<YOUR_POPUP_VIEW
.... />
</RelativeLayout>

  1. WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
    layoutParams.dimAmount = #WHAT_EVER_VALUE_YOU_WANT_TO_KEEP; //Generally in between 0.70f to 0.80f
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    getWindow().setAttributes(layoutParams);

Dim or Blur background in activity

I solved this problem by setting the background to the layout of the pop-up window with the following.

android:background="#80FFFFFF"

Thnaks..And it works as expected.



Related Topics



Leave a reply



Submit