为什么我的默认警报对话框按钮文本为白色?

问题描述

我的应用程序设置如下:

build.gradle

implementation 'com.google.android.material:material:1.1.0'

styles.xml

    <style name="AlertDialogTheme" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
        <item name="buttonbarNegativeButtonStyle">@style/NegativeButtonStyle</item>
        <item name="buttonbarPositiveButtonStyle">@style/PositiveButtonStyle</item>
    </style>

    <style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="android:color">@color/colorPrimary</item>
    </style>

    <style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="android:color">@color/colorPrimary</item>
    </style>

CheckoutFragment.kt

   private fun createConfirmOrderDialog() {
       val builder = AlertDialog.Builder(requireContext(),R.style.AlertDialogTheme)
       builder.setTitle(getString(R.string.confirm_order))
           .setMessage(dialogPrompt)
           .setPositiveButton(R.string.confirm) { dialog,_ ->
               viewmodel.placeOrder()
               dialog.dismiss()
           }
           .setNegativeButton(R.string.cancel) { dialog,_ ->
               dialog.dismiss()
           }
       builder.show()
  }

colors.xml

<color name="colorAccent">#F1CB1A</color> // I have this added to the base theme

但是,此设置显示一个对话框,其中按钮文本不可见,因为文本和背景均为白色。

The resulting dialog

我该如何解决

解决方法

使用 MaterialAlertDialogBuilder 代替AlertDialog.Builder

    MaterialAlertDialogBuilder(context)
        .setTitle("Title")
        .setMessage(dialogPrompt)
        .setPositiveButton("OK",listener)
        .show()

按钮的默认颜色基于colorPrimary颜色。

如果要使用自定义颜色,可以使用:

    MaterialAlertDialogBuilder(context,R.style.AlertDialogTheme)

具有这种风格

<style name="AlertDialogTheme" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
    <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
</style>

<style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    <item name="android:textColor">@color/.....</item>
</style>

<style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    <item name="android:textColor">@color/....</item>
</style>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...