应用ThemeOverlay自定义MaterialAlertDialogBuilder对话框的主题



我的应用程序主题是这样设置的:

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

但是当我使用MaterialAlertDialogBuilder时,文本对比度非常差(因为材料对话框使用colorOnSurface与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)问题?这不是应用主题叠加的正确方法吗?或者是否有其他方法让警报对话框使用@color/appColorOnSurfaceHighContrast?

我通过使用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.MaterialComponents.Dialog更改为ThemeOverlay.MaterialComponents.Dialog.Alert修复了触摸区域问题,但我仍然得到一个AppCompat(非材料)主题。

  2. 将父主题覆盖从ThemeOverlay.MaterialComponents.Dialog.Alert更改为ThemeOverlay.MaterialComponents.MaterialAlertDialog,固定主题使其显示为材质。

更新:看起来ThemeOverlay.MaterialComponents.Dialog.Alert是用于alertDialogThemeThemeOverlay.MaterialComponents.MaterialAlertDialog是用于materialAlertDialogTheme。见:https://github.com/material-components/material-components-android/blob/master/lib/java/com/google/android/material/dialog/res/values/themes.xml L60

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

最新更新