使用哪个主题来为AlertDialog自动调整颜色以适应白天/黑夜主题?

5

如果应用程序调用AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);,则预计显示暗色主题,如果没有,则应用程序将具有浅色主题。

使用AlertDialog.Builder(this),并希望应用一种主题,以便在MODE_NIGHT中显示具有暗色主题的对话框,否则,对话框将显示浅色主题,类似于下面的内容(但是android.R.style.Theme_Material_Dialog将导致对话框始终处于暗色主题)

AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog)

AlertDialog有一个主题吗?还是必须定义两个主题并检查模式,然后分别使用相应的主题进行编码?

2个回答

10

您需要在 styles.xml 中定义您的警告对话框。

<style name="MyDialogStyle" parent="Theme.AppCompat.DayNight.Dialog.Alert"/>

在你的代码中
AlertDialog.Builder(this, R.style.MyDialogStyle)

试一下吧!


我们必须为每个对话框设置这种样式,或者您可以在style.xml中为活动使用的主题设置暗色警报。 - Vijay

1

添加到您的主题样式中:

        <item name="alertDialogTheme">@style/Theme.AppCompat.DayNight.Dialog.Alert</item>
        <item name="android:alertDialogTheme">@style/Theme.AppCompat.DayNight.Dialog.Alert</item>

使用AppCompat的对话框

import androidx.appcompat.app.AlertDialog;

AlertDialog alertDialog = new AlertDialog.Builder(context).create()

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