android - 如何使用样式全局更改 AlertDialog 上的按钮文本颜色?

标签 android android-alertdialog android-theme android-styles material-components-android

当我这样做时在 android O 上:

  <style name="MyTheme" parent="@android:style/Theme.Material.Light.NoActionBar"> 

    <item name="android:textColor">#ff0000</item>

  </style>

我的警报对话框的文本按钮颜色改变了,但这在 Lollipop 下不起作用。更糟糕的是,在 Lollipop 上,它会更改警报对话框标题的颜色。

如何从 kitkat 到 android O 我可以全局更改所有 alertdialog 按钮的字体颜色?

最佳答案

借助 MaterialComponents 主题和 MaterialAlertDialogBu​​ilder,您可以使用应用主题中的 materialAlertDialogTheme 属性全局定义样式。

类似于:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
   <item name="materialAlertDialogTheme">@style/My_MaterialAlertDialog</item>
</style>

然后你可以定义一个自定义样式:

  <style name="My_MaterialAlertDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <!-- Style for positive button -->
    <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
    <!-- Style for negative button -->
    <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
    <!-- Style for neutral button -->
    <item name="buttonBarNeutralButtonStyle">@style/NeutralButtonStyle</item>
  </style>

按钮样式定义为:

  <style name="PositiveButtonStyle" parent="@style/Widget.MaterialComponents.Button">
    <item name="android:textColor">#FFFFFF</item>
    <item name="backgroundTint">@color/primaryDarkColor</item>
  </style>

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

  <style name="NueutralButtonStyle" parent="@style/Widget.MaterialComponents.Button.TextButton.Dialog">
    ....
  </style>

使用库的 1.1.0 版本,您还可以使用自定义样式中的 materialThemeOverlay 简单地覆盖默认颜色:

  <style name="My_MaterialAlertDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
      <item name="materialThemeOverlay">@style/DialogButtonOverlay</item>
  </style>

  <style name="DialogButtonOverlay">
    <item name="colorPrimary">@color/...</item>
  </style>

关于android - 如何使用样式全局更改 AlertDialog 上的按钮文本颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52836424/

相关文章:

android - Google Play Services maps 6.5 如何手动触发 map 工具栏

android - Flutter 应用程序,每天在 x 时间检查,看看我是否需要向用户发送本地通知

java - 如何禁用Android中的对话框按钮?

android - style.xml 和 theme.xml android studio 之间的区别?

android - 以编程方式获取主题属性

android - 从服务关闭 Activity 的正确方法是什么?

java - 为什么来自 AlertDialog 的输入不显示在 RecyclerView 中?

android - 如何获取当前主题操作栏背景颜色?

android - 使用 fragment 时 viewModelFactory 变量尚未初始化