安卓如何调整自定义对话框的背景透明度?

6

如标题所述,我似乎无法使我制作的自定义对话框的背景变暗。无数在线解决方案提到了下面第一段代码中的最后3行代码,但这对对话框的用户界面没有任何影响。

请参考以下代码:

Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog);
TextView textView = (TextView) dialog.findViewById(R.id.textView);
textView.setText("Custom Text Example");
dialog.show();

WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
layoutParams.dimAmount = .7f;
dialog.getWindow().setAttributes(layoutParams);

自定义对话框的布局xml文件如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/progressDialogCustom"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/dialog_black"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:textColor="@android:color/white"
        android:text="Updating Profile . . ." />

</LinearLayout>
@drawable/dialog_black文件如下:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="@android:color/background_dark" />

    <corners
        android:bottomLeftRadius="7dp"
        android:bottomRightRadius="7dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp" />

    <stroke
        android:width="1px"
        android:color="@android:color/darker_gray" />

    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />

</shape>

这个对你有帮助吗:https://dev59.com/ZWkv5IYBdhLWcg3wwTdm? - android developer
谢谢,设置灯光亮度的相关信息已经包含在我的代码中了,(供参考,第一个片段中的最后3行)。 - rperryng
但是你使用了吗:dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);? - android developer
该方法已被弃用。而且在实施后也没有解决问题。 - rperryng
奇怪,我记得它甚至在更新的安卓版本上也能运行。也许现在已经不能用了。 - android developer
1个回答

13

你尝试过添加以下内容吗:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

只有当这个标志存在时,dimAmount 才会被忽略。


是的。目前我只有一个解决方法,就是将对话框设置为全屏,并将其父视图设置为仅包含半透明的1px * 1px 9 patch drawable。 - rperryng
是的,这行代码在起作用。我已经添加了dimAmount,但没有这行代码就不起作用。 - Ravi Yadav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接