Android开发WindowManager如何让背景透明呢?
效果如下:
可以看到,弹出的窗口背景是有点透明的。
如果我们不做任何设置,直接添加到window中,默认是黑色的背景。
首先,设置LayoutParams
设置这个参数:
layoutParams.format = PixelFormat.TRANSPARENT;
主要的代码:
public void showMsgDialog() {
ICLogger.d("showMsgDialog..." + isShow);
if (isShow) {
return;
}
isShow = true;
Context context = ICApplication.sContext;
windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//设置属性
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.format = PixelFormat.TRANSPARENT;
layoutParams.packageName = context.getPackageName();
layoutParams.gravity = Gravity.CENTER;
//加载布局
view = View.inflate(context, R.layout.battery_charge_tips_dialog_layout, null);
//设置适配器
initView(view);
windowManager.addView(view, layoutParams);
}
然后,布局上设置一个有透明度的颜色
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dd000000">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/shape_black_dialog_bg"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tips_charge_text"
android:textColor="@color/white"
android:textSize="28sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="@drawable/selector_urgent_call_bg"
android:paddingLeft="14dp"
android:paddingTop="4dp"
android:paddingRight="14dp"
android:paddingBottom="4dp"
android:text="@string/urgent_call_text"
android:textColor="@color/white"
android:textSize="24sp" />
</LinearLayout>
</FrameLayout>
okay,这样子就可以实现有透明度的背景了。