更改弹出对话框的背景颜色。

77

我编写了一个显示弹出对话框的Android代码,但我想将背景颜色从黑色更改为白色,然后更改文字的颜色。

这是对话框的代码:

mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);

    if (!welcomeScreenShown) {


        String whatsNewText = getResources().getString(R.string.Text);
        new AlertDialog.Builder(this).setMessage(whatsNewText).setPositiveButton(
                R.string.ok, new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putBoolean(welcomeScreenShownPref, true);
        editor.commit(); // Very important to save the preference
    }
11个回答

129

为了进一步说明 @DaneWhite 的答案,您不必依赖内置主题。 您可以轻松提供自己的样式:

<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:background">@color/myColor</item>
</style>

然后将其应用于Builder构造函数中:

Java:

AlertDialog alertDialog = new AlertDialog.Builder(getContext(), R.style.MyDialogTheme)
        ...
        .create();

Kotlin:

var alertDialog = AlertDialog.Builder(context, R.style.MyDialogTheme)
        ...
        .create()

无论您使用的是android.support.v7.app.AlertDialog还是android.app.AlertDialog,这都应该能够正常工作。

这比@DummyData的答案更好的地方在于,您不需要调整对话框的大小。如果您设置窗口的背景drawable,您会覆盖一些现有的尺寸信息,并得到一个宽度不标准的对话框。

如果您在主题上设置背景,然后将主题设置为对话框,您会得到一个按您想要的颜色着色但仍具有正确宽度的对话框。


2
我该如何改变文本和按钮的颜色? - Pierry
3
你应该使用android:windowBackground主题属性。android:background会改变每个View的背景颜色。 - BladeCoder
3
实际上,backgroundwindowBackground都会移除对话框窗口的圆角。如果您想设置颜色,应该使用colorBackground属性。 - Nikolai
此解决方案还将对话框中的文本颜色更改为更深的颜色。 - Vitaly
如果使用MaterialComponents,我发现唯一可以在不移除圆角的情况下正常工作的方法是设置android:backgroundTint - lecker909

65
如果您只需要一个轻量级的主题,并且不关心具体的颜色,那么您可以将主题ID传递给AlertDialog.Builder构造函数。

如果你只想要一个轻便的主题而不关心具体的颜色,那么你可以在AlertDialog.Builder构造函数中传递一个主题ID。

AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)...
或者
AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)...

8
现在它说已弃用了?现在有什么建议吗? - Dinesh
5
如果您正在使用Android Studio,它会直接告诉您替换为:已弃用,请使用android.R.style.Theme_Material_Light_Dialog_Alert - tir38

51

感谢Sushil

按照惯例创建您的AlertDialog:

AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
Dialog dialog = dialog.create();
dialog.show();

调用您的对话框上的show()方法后,可以像这样设置背景色:

dialog.getWindow().setBackgroundDrawableResource(android.R.color.background_dark);

5
请注意,虽然这将设置背景颜色,但您将替换先前包含宽度尺寸的背景可绘制对象。如果您不更新背景可绘制对象,则生成的对话框可能会有不同的大小。请谨慎操作。 - tir38
我希望我们可以通过主题资源使用一些样式属性来完成它。我认为应该有这种可能性来设置不仅是颜色,而且是任何其他可绘制的背景资源。 - Cícero Moura

32

要更改应用程序中所有对话框和弹出窗口的背景颜色,请使用colorBackgroundFloating属性。

<style name="MyApplicationTheme" parent="@style/Theme.AppCompat.NoActionBar">
...
<item name="colorBackgroundFloating">
    @color/background</item>
<item name="android:colorBackgroundFloating" tools:targetApi="23">
    @color/background</item>
...
</style>

文档:

colorBackgroundFloating


25

使用Material Components Library,你可以直接使用默认的MaterialAlertDialogBuilder

    new MaterialAlertDialogBuilder(AlertDialogActivity.this,
        R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog_Background)
        .setTitle("Dialog")
        .setMessage("Message...  ....")
        .setPositiveButton("Ok", /* listener = */ null)
        .show();

主题叠加层ThemeOverlay_MaterialComponents_MaterialAlertDialog_Background的位置:

  <!-- Alert Dialog -->
  <style name="ThemeOverlay.MaterialComponents.MaterialAlertDialog_Background" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <!-- Background Color-->
    <item name="android:background">@color/.....</item>
    <!-- Text Color for title and message -->
    <item name="colorOnSurface">@color/......</item>
    <!-- Style for positive button -->
    <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
    <!-- Style for negative button -->
    <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
  </style>

  <style name="PositiveButtonStyle" parent="@style/Widget.MaterialComponents.Button">
    <!-- text color for the button -->
    <item name="android:textColor">@color/.....</item>
    <!-- Background tint for the button -->
    <item name="backgroundTint">@color/primaryDarkColor</item>
  </style>

输入图像描述在此


我正在查看 https://material.io/components/dialogs/android#full-screen-dialog,其中容器颜色元素没有属性。我试图编辑 colorSurface 属性,但是没有任何效果。感谢您的回答。 - Shivam Pokhriyal

16

对于任何名为myDialog的对话框,在调用myDialog.show();之后,您可以调用:

myDialog.getWindow().getDecorView().getBackground().setColorFilter(new LightingColorFilter(0xFF000000, CUSTOM_COLOR));

其中CUSTOM_COLOR以8位十六进制格式表示,例如0xFF303030。这里,FF是Alpha值,其余部分是颜色的十六进制表示。


2
+1,比使用“setBackgroundDrawableResource”更好的解决方案,因为你不必担心大小或形状组件。你还可以使用“... .setColorFilter(int color, Mode mode)”,其中“color”将是你可以从类似于“getColor(int resId)”的信息中获取的颜色码int值,而对于“mode”,你可以使用“Mode.SRC”以完全覆盖以前的颜色。 - VerumCH

3
您可以创建一个自定义的AlertDialog并使用XML布局。在布局中,您可以设置背景颜色和文字颜色。
类似这样:
Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
LayoutInflater inflater = (LayoutInflater)ActivityName.this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_layout,(ViewGroup)findViewById(R.id.layout_root));
dialog.setContentView(view);

1
但是我能不能只添加一行代码来改变颜色,而不必做所有这些事情呢? - Rick
7
你可以尝试这个:getWindow().setBackgroundDrawableResource(android.R.color.white);它将设置窗口背景为白色。 - Sushil
希望你正在正确的位置编写代码,并且只弹出了你的警告对话框。 - Sushil
如果你加上 YOUR_DIALOG.getWindow().setBackgroundDrawableResource(android.R.color.white); 这行代码,它就能正常工作了。 - Hossein Mansouri

3

如果想要更改对话框按钮和背景颜色,您需要扩展对话框主题,例如:

<style name="MyDialogStyle" parent="android:Theme.Material.Light.Dialog.NoActionBar">
    <item name="android:buttonBarButtonStyle">@style/MyButtonsStyle</item>
    <item name="android:colorBackground">@color/white</item>
</style>

<style name="MyButtonsStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
    <item name="android:textColor">@color/light.blue</item>
</style>

接下来,您需要将此自定义样式传递给对话框构建器,例如:

AlertDialog.Builder(requireContext(), R.style.MyDialogStyle)

如果你想改变对话框内文本的颜色,可以将自定义视图传递给此构建器:

AlertDialog.Builder.setView(View)

或者
AlertDialog.Builder.setView(@LayoutResource int)

0

你可以在drawable中创建一个形状XML

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="@color/white" />
</shape>


在创建警告对话框后添加此行。
alertDialog.getWindow().setBackgroundDrawable(ContextCompat.getDrawable(ATextActivity.this,R.drawable.color_drawable));

如果您不想创建XML,可以尝试下面的代码
创建一个颜色的可绘制对象
ColorDrawable colorDrawable = new ColorDrawable(ContextCompat.getColor(this, R.color.white));

alertDialog.getWindow().setBackgroundDrawable(colorDrawable);

-1
alertDialog.getWindow().setBackgroundDrawable(contex.getDrawable(R.drawable.container_dialog));

感谢您对Stack Overflow社区做出贡献的兴趣。这个问题已经有很多答案了,其中一个答案已经得到社区的广泛验证。您确定您的方法之前没有被提到过吗?如果是这样的话,能否解释一下您的方法与之前的方法有何不同,以及在什么情况下您的方法可能更好,或者为什么您认为之前的答案不够满意。您能否编辑您的答案并提供解释? - undefined

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