【问题标题】:Android, setting the theme in the style does not workAndroid,在样式中设置主题不起作用
【发布时间】:2021-05-19 12:58:19
【问题描述】:

我知道

样式指定特定类型视图的属性。例如,一种样式可能指定按钮的属性。您在样式中指定的每个属性都是您可以在布局文件中设置的属性。通过将所有属性提取到一个样式中,可以很容易地跨多个小部件使用和维护它们。

主题定义了一组命名资源,这些资源可以被样式、布局、小部件等引用。主题将语义名称(如 colorPrimary)分配给 Android 资源。

所以,我想我可以从样式文件中设置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" />

【问题讨论】:

    标签: android material-design android-theme


    【解决方案1】:

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

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

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

    <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是在材质视图源码里面使用的,所以要确切知道主题样式或属性的效果,你应该查看视图源码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      相关资源
      最近更新 更多