【发布时间】:2021-06-30 15:04:16
【问题描述】:
我正在尝试在我的应用中自定义工具栏的外观。
目标
我想设置工具栏的标题颜色和背景颜色。
我阅读了有关主题和样式的工作原理,因此我能够尝试一些解决方案。
我发现标题颜色由app:titleTextColor 属性管理,背景颜色由android:background 属性管理。
前提
要知道如何操作,就必须知道我们需要修改的小部件的样式是如何管理的。
基本工具栏样式在Widget.MaterialComponents.Toolbar 样式中定义,如下所示。
<style name="Widget.MaterialComponents.Toolbar" parent="Widget.AppCompat.Toolbar">
<item name="titleTextAppearance">?attr/textAppearanceHeadline6</item>
<item name="titleTextColor">?android:attr/textColorPrimary</item>
<item name="subtitleTextAppearance">?attr/textAppearanceSubtitle1</item>
<item name="subtitleTextColor">?android:attr/textColorSecondary</item>
<!-- Overrides minimum height in landscape to avoid headline6 and subtitle1 height concerns. -->
<item name="android:minHeight">@dimen/mtrl_toolbar_default_height</item>
<item name="maxButtonHeight">@dimen/mtrl_toolbar_default_height</item>
</style>
这里titleTextColor的值设置为?android:attr/textColorPrimary。
所以我的第一次尝试只是在我的应用主题中添加 android:textColorPrimary 属性的 ovverride。
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
<item name="android:textColorPrimary">@color/white</item>
</style>
结果:这行得通。
为了同时设置背景,我决定创建一个自定义工具栏样式来放置背景定义,因此我将主题更改如下。
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
...
<!-- Customize your theme here. -->
<item name="toolbarStyle">@style/MyToolbarStyle</item>
</style>
<style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar">
<item name="android:textColorPrimary">@color/white</item>
<item name="android:background">?attr/colorPrimary</item>
</style>
结果: 这不起作用。 android:background 已应用,但 android:textColorPrimary 未应用。
直接在MyToolbarStyle 中设置titleTextColor 的值是可行的。
<style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar">
<item name="titleTextColor">?attr/colorOnPrimary</item>
<item name="android:background">?attr/colorPrimary</item>
</style>
我还尝试设置我覆盖 Android attribute:textColorPrimary 的工具栏主题,如下所示。
<style name="Base_ToolbarStyle" parent="Widget.MaterialComponents.Toolbar">
<item name="android:background">?attr/colorPrimary</item>
<item name="android:theme">@style/Base_ToolbarTheme</item>
</style>
<style name="Base_ToolbarTheme">
<item name="android:textColorPrimary">@color/white</item>
<item name="android:textColorSecondary">@color/white</item>
</style>
结果:这也不行。
现在我对我的测试结果有点困惑。
为什么无法覆盖自定义样式中的android:textColorPrimary?
【问题讨论】:
标签: android material-design android-toolbar android-theme