如何从MaterialComponents.DayNight主题更改工具栏文本颜色?

15

我在我的应用程序中使用了MaterialComponents.DayNight主题。在白天模式下,工具栏文本颜色是黑色的。但是当我切换到夜间模式时,工具栏文本颜色仍然是黑色,因此不再可见。

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">

我想在夜间模式下将工具栏文本颜色更改为白色。我该怎么做?


你解决了这个问题吗? - android developer
1
@androiddeveloper 我已在下面发布了一个答案。 - Christian Brüggemann
好的,谢谢。这里我给你点赞+1 :) - android developer
5个回答

23

只需在您的布局中使用以下样式(它也适用于 androidx.appcompat.widget.Toolbar):

<com.google.android.material.appbar.MaterialToolbar
    style="@style/Widget.MaterialComponents.Toolbar.Primary"

接下来,在 values-night/colors.xml 文件中定义 colorOnPrimary

然后还有很多可选方案。
您可以在应用程序主题中全局自定义工具栏的样式,方法如下:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
  <item name="toolbarStyle">@style/MyToolbar</item>
</style>

使用:

  <style name="MyToolbar" parent="Widget.MaterialComponents.Toolbar.Primary">
    <item name="titleTextColor">@color/.....</item>
  </style>

并在 values/colors.xmlvalues-night/colors.xml 中定义颜色。

或者在工具栏中应用样式。

<com.google.android.material.appbar.MaterialToolbar
    style="@style/MyToolbar"

或者只需使用以下方法覆盖主题:

<com.google.android.material.appbar.MaterialToolbar
   android:theme="@style/MyThemeOverlay_Toolbar"

使用:

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <item name="colorOnPrimary">@color/...</item>
  </style>

1
正确的是...谢谢伙计 - Betini O. Heleno

7

将您的父级主题设置为 parent="Theme.MaterialComponents.DayNight.DarkActionBar.Bridge"

使用此设置,您可以在 MaterialComponents 的全局 DayNight 主题上保留 ActionBar 的原始主题,并具有 DarkActionBar 属性。


6
将以下内容添加到您的主题中:

<item name="android:itemTextAppearance">@style/PopupMenuTextAppearance</item>

接下来,根据需要在styles.xml中添加相应的样式:

<style name="PopupMenuTextAppearance" parent="TextAppearance.AppCompat.Menu">
    <item name="android:textColor">?attr/colorOnBackground</item>
</style>

?attr/colorOnBackground 可在 Material Components library 中找到。如果您没有使用该库,您可以使用?android:attr/textColorPrimary


2
在我看来,你应该将样式设置为noActionbar,并设计新的工具栏并自定义它。"最初的回答"。

1

我在styles.xml文件中使用了以下这两行代码:

<item name="colorControlNormal">@android:color/white</item>
<item name="android:textColorPrimary">@android:color/white</item>

它将工具栏文本和工具栏X图标的颜色更改为白色。

整个代码如下:

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">#00695c</item>
        <item name="colorPrimaryVariant">#439889</item>
        <item name="colorOnPrimary">#ffffff</item>
        <item name="colorSecondary">#007769</item>
        <item name="colorSecondaryVariant">#48a697</item>
        <item name="colorOnSecondary">#ffffff</item>
        <item name="colorControlNormal">@android:color/white</item>
        <item name="android:textColorPrimary">@android:color/white</item>
    </style>
</resources>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接