我目前正在创建一个应用程序,其中有一个
MaterialToolbar
小部件。我想将图标颜色设置为白色。
我尝试遵循这个问题中接受的答案,但是,它不起作用。在 styles.xml 中添加 colorControlNormal
不起作用。
这是我的 MaterialToolbar xml 代码:
<com.google.android.material.appbar.MaterialToolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/topToolbar"
android:background="@color/colorPrimaryDark"
app:title="Revo"
app:titleTextColor="@android:color/white"
app:menu="@menu/menu_floatingsearchview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
我能做什么?
编辑、解决方案和说明
感谢大家的精彩回答。我设法找到了一个解决方案,其中包括两个解决方案和另一个问题。
在this问题中,有人问为什么
colorControlNormal
不起作用。接受的答案是,在矢量线中,您必须更改赋予 android:fillColor
的值,并将其替换为 ?attr/colorControlNormal
。执行此技巧,项目 colorControlNormal,将控制所需的图标颜色。
在应用程序main样式中,您需要放置:
<item name="colorControlNormal">@android:color/white</item>
然后,在所需的图标中,您需要将
path
:
android:fillColor="?attr/colorControlNormal"
就是这样!现在图标将获得指定给 colorControlNormal 属性的颜色!
您可以使用:
<com.google.android.material.appbar.MaterialToolbar
app:menu="@menu/toolbar_menu"
style="@style/Widget.MaterialComponents.Toolbar.Primary
android:theme="@style/MyThemeOverlay_Toolbar"
.../>
与:
<style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
<!-- color used by navigation icon and overflow icon -->
<item name="colorOnPrimary">@color/....</item>
</style>
几天前这个问题困扰了我。 我最终这样做了:
将所需的颜色设置为
colors.xml
中的变量
然后直接在drawable的源码中设置这个颜色
android:fillColor="@color/toolbarTextColor"
MaterialToolbar
中设置文本颜色时使用相同的变量。
toolbar.menu.forEach { menuItem -> MenuItemCompat.setIconTintList(
menuItem, getColorStateList(requireContext(), R.color.primary_color_state))
颜色选择器是这样的:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:color="?attr/colorPrimary"/>
<item android:state_selected="true" android:color="?attr/colorPrimary"/>
<item android:state_pressed="true" android:color="?attr/colorPrimaryDark"/>
<item android:color="?attr/colorPrimary"/>
</selector>