如何正确更改 MaterialAlertDialog 文本颜色?

How to change MaterialAlertDialog text color properly?

我尝试仅使用 Material 组件中的小部件,但在许多情况下,没有记录如何实现样式。

让我们考虑一下MaterialAlertDialog

每次我想显示一个对话框,我调用这样的代码部分:

MaterialAlertDialogBuilder(context, R.style.Theme_MyApp_Dialog_Alert)
    .setTitle("Title")
    .setMessage("This is message.")
    .setPositiveButton(R.string.ok) { _, _ -> }
    .show()

如您所见,我正在使用自定义主题。

<style name="Theme.MyApp.Dialog.Alert" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <!-- attributes here -->
</style>

问题是某些属性不起作用。例如 textColor。所以问题是如何更改 MaterialAlertDialog 中的 body 或标题文本颜色?

我使用最新版本的 Material 组件 - 1.1.0-alpha07

PS.

我不确定哪个主题应该是 parent。在 Material Theme Builder 中,他们使用 @style/ThemeOverlay.MaterialComponents.Dialog.Alert,这实际上给出了 "old" 的对话框外观。

修改样式如下

<style name="Theme.MyApp.Dialog.Alert" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <item name="materialAlertDialogTitleTextStyle">@style/MaterialAlertDialogText</item>
</style>

创建 MaterialAlertDialogText 样式并设置 textColor

<style name="MaterialAlertDialogText" parent="@style/MaterialAlertDialog.MaterialComponents.Title.Text">
    <item name="android:textColor">@color/yourTextColor</item>
</style>

您可以使用以下方法简单地覆盖默认颜色:

  <style name="Theme.MyApp.Dialog.Alert" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">

     <!-- Text Color for title and message -->
     <item name="colorOnSurface">@color/....</item>
     ....
  </style> 

否则,您可以自定义标题和 body 文本使用的样式:

  <style name="Theme.MyApp.Dialog.Alert" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">    
      <!-- Title -->
      <item name="materialAlertDialogTitleTextStyle">@style/MyTitle_MaterialAlertDialog.MaterialComponents.Title.Text</item>

     <!-- Body -->
     <item name="materialAlertDialogBodyTextStyle">@style/BodyTextAppearance.MaterialComponents.Body2</item>
  </style>

  <style name="MyTitle_MaterialAlertDialog.MaterialComponents.Title.Text" parent="@style/MaterialAlertDialog.MaterialComponents.Title.Text">
    <item name="android:textColor">@color/...</item>
    <item name="android:textAppearance">@style/....</item>
  </style>

  <style name="BodyTextAppearance.MaterialComponents.Body2" parent="@style/MaterialAlertDialog.MaterialComponents.Body.Text">
    <item name="android:textColor">@color/....</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textAllCaps">true</item>
    <item name="fontFamily">sans-serif-condensed-light</item>
  </style>