应用 ThemeOverlay 自定义主题 MaterialAlertDialogBu​​ilder 对话框

时间:2021-02-11 07:14:45

标签: android android-theme android-dialogfragment android-dialog material-components-android

我的应用主题设置如下:

<style name="Theme.App" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    <item name="colorOnSurface">@color/appColorOnSurface</item>
...
</style>

但是当我使用 MaterialAlertDialogBuilder 时,文本对比度非常差(因为材质对话框使用 colorOnSurface with 60% alpha,而不是 textColorPrimary)。所以我尝试使用这个 ThemeOverlay:

<style name="ThemeOverlay.App.Dialog.HighContrast" parent="ThemeOverlay.MaterialComponents.Dialog">
    <item name="colorOnSurface">@color/appColorOnSurfaceHighContrast</item>
</style>

并像这样应用它:

<style name="Theme.App" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    <item name="materialAlertDialogTheme">@style/ThemeOverlay.App.Dialog.HighContrast</item>
    <item name="colorOnSurface">@color/appColorOnSurface</item>
    ...
</style>

然而,这会导致在对话框中显示项目列表时出现问题。每个项目的触摸区域仅限于显示的文本区域,而不是像往常一样拉伸对话框的宽度。

此外,主题似乎不是 Material 风格,而是 AppCompat 风格。

为什么 ThemeOverlay 方法会导致意外的触摸区域(好像 WRAP_CONTENT)问题?这不是应用 ThemeOverlay 的正确方法吗?或者还有其他方法可以让警报对话框使用 @color/appColorOnSurfaceHighContrast 吗?

1 个答案:

答案 0 :(得分:0)

我通过使用 ThemeOverlay.MaterialComponents.MaterialAlertDialog 而不是 ThemeOverlay.MaterialComponents.Dialog.Alert 来解决这个问题,并且还使用 materialAlertDialogBodyTextStyle 来确保仅设置了对话框文本正文的样式:

<style name="ThemeOverlay.App.Dialog.HighContrast" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <item name="materialAlertDialogBodyTextStyle">@style/MaterialAlertDialog.App.Body.Text.HighContrast</item>
</style>

<style name="MaterialAlertDialog.App.Body.Text.HighContrast" parent="@style/MaterialAlertDialog.MaterialComponents.Body.Text">
    <item name="android:textColor">@color/appColorOnSurfaceHighContrast</item>
</style>

但为什么 AndroidStudio 自动完成只显示 ThemeOverlay.MaterialComponents.Dialog.Alert 而不是 ThemeOverlay.MaterialComponents.MaterialAlertDialog

注意:这里实际上有两个问题:

  1. 将父 ThemeOverlay 从 ThemeOverlay.MaterialComponents.Dialog 更改为 ThemeOverlay.MaterialComponents.Dialog.Alert 修复了触摸区域问题,但我仍然获得 AppCompat(非 Material)主题。

  2. 将父 ThemeOverlay 从 ThemeOverlay.MaterialComponents.Dialog.Alert 更改为 ThemeOverlay.MaterialComponents.MaterialAlertDialog 修复了主题以使其显示为 Material。

更新:看起来 ThemeOverlay.MaterialComponents.Dialog.AlertalertDialogTheme 一起使用,而 ThemeOverlay.MaterialComponents.MaterialAlertDialogmaterialAlertDialogTheme 一起使用。请参阅:https://github.com/material-components/material-components-android/blob/master/lib/java/com/google/android/material/dialog/res/values/themes.xml#L60

然而,这仍然不能解释为什么后者不自动完成。

相关问题