Android Dialog 怎么加蒙层
要给 Android Dialog 加蒙层,可以使用以下步骤:
- 创建一个透明的背景蒙层布局文件,比如可以命名为
dialog_background.xml,内容如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#80000000" />
这里的 #80000000 表示半透明黑色背景,可以根据需要改变颜色和透明度。
- 在创建 Dialog 的代码中,先通过
LayoutInflater加载蒙层布局文件,并将其添加到 Dialog 的根布局中。代码示例:
// 加载蒙层布局文件
View backgroundView = LayoutInflater.from(context).inflate(R.layout.dialog_background, null);
// 创建 Dialog,并将蒙层布局添加到 Dialog 的根布局中
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setView(view);
AlertDialog dialog = builder.create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().addContentView(backgroundView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
- 在需要显示 Dialog 的时候,调用 Dialog 的
show()方法即可。
这样就可以给 Android Dialog 加上蒙层了。注意,如果想让蒙层可以响应点击事件,可以在布局文件中添加一个透明的点击响应层,并设置其 onClick 监听器。具体实现方式可以参考如下代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 蒙层背景 -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#80000000"
android:onClick="onBackgroundClicked" />
<!-- 点击响应层 -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="onDialogClicked" />
<!-- Dialog 内容布局 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#FFFFFF"
android:padding="16dp">
<!-- Dialog 内容 -->
</LinearLayout>
</RelativeLayout>
在 Java 代码中,可以再实现两个点击监听器,分别对应蒙层和 Dialog 的点击事件:
public void onBackgroundClicked(View view) {
// 点击蒙层时,关闭 Dialog
dialog.dismiss();
}
public void onDialogClicked(View view) {
// 点击 Dialog 内容时,不做任何处理
}
``
原文地址: https://www.cveoy.top/t/topic/cqaa 著作权归作者所有。请勿转载和采集!