Android,在样式中设置主题不起作用

Android, setting the theme in the style does not work

我知道

A style specifies attributes for a particular type of view. For example, one style might specify a button's attributes. Every attribute you specify in a style is an attribute you could set in the layout file. By extracting all the attributes to a style, it's easy to use and maintain them across multiple widgets.

A theme defines a collection of named resources which can be referenced by styles, layouts, widgets, and so on. Themes assign semantic names, like colorPrimary, to Android resources.

所以,我想我可以从样式文件中设置 theme 属性。

为什么这不起作用?

<!-- Customize your theme here. -->
<item name="toolbarStyle">MyToolbarStyle</item>
...

<style name="MyToolBarTheme" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <item name="android:textColorPrimary">@color/white</item>
    <item name="colorOnPrimary">@color/white</item>
</style>

<style name="MyToolbarStyle" parent="Widget.AppCompat.Toolbar">
    <item name="theme">@style/MyToolBarTheme</item>
</style>

相反,这可以正常工作:

    <com.google.android.material.appbar.MaterialToolbar
    android:id="@+id/homeToolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/MyToolBarTheme" />

我发现如果定义样式本身由主题设置,则不会设置theme属性,只有在设计器中设置样式时才设置。

另一方面,materialThemeOverlay 属性工作正常并且实际应用了主题。

我在 material 设计主题定义中发现了一条评论:

<style name="Widget.MaterialComponents.Toolbar.Primary">
<item name="android:elevation" ns2:ignore="NewApi">@dimen/design_appbar_elevation</item>
<item name="android:background">?attr/colorPrimary</item>
<item name="titleTextColor">?attr/colorOnPrimary</item>
<item name="subtitleTextColor">@color/material_on_primary_emphasis_medium</item>
<!-- Note: this theme overlay will only work if the style is applied directly to a Toolbar. -->
<item name="android:theme">@style/ThemeOverlay.MaterialComponents.Toolbar.Primary</item>

因此,就我而言,这按预期工作:

<!-- Customize your theme here. -->
<item name="toolbarStyle">MyToolbarStyle</item>
...

<style name="MyToolBarTheme" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <item name="android:textColorPrimary">@color/white</item>
    <item name="colorOnPrimary">@color/white</item>
</style>

<style name="MyToolbarStyle" parent="Widget.AppCompat.Toolbar">
    <item name="materialThemeOverlay">@style/MyToolBarTheme</item>
</style>

更新

样式和主题如何应用于视图在很大程度上取决于视图的实现方式。

materialThemeOverlay在material查看源代码中使用,所以要确切了解主题样式或属性的效果,您应该查看查看源代码。