【问题标题】:How do I change the background color of the ActionBar in the new MaterialComponents如何在新 MaterialComponents 中更改 ActionBar 的背景颜色
【发布时间】:2019-02-28 20:47:23
【问题描述】:
我正在使用新的MaterialComponents,我的应用主题是:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
<item name="colorPrimary">@color/primaryColor</item>
<item name="colorPrimaryDark">@color/primaryDarkColor</item>
<item name="colorAccent">@color/secondaryColor</item>
</style>
如何改变ActionBar的背景颜色
我知道this question,但它已经过时并且不使用MaterialComponents
我不想将工具栏添加到每个屏幕只是为了更改背景颜色。
【问题讨论】:
标签:
android
android-layout
android-actionbar
android-styles
material-components-android
【解决方案1】:
您需要根据背景颜色使用ThemeOverlay.MaterialComponents.ActionBar 或ThemeOverlay.MaterialComponents.Dark.ActionBar。
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
<item name="colorPrimary">@color/primaryColor</item>
<item name="colorPrimaryDark">@color/primaryDarkColor</item>
<item name="colorAccent">@color/secondaryColor</item>
<item name="actionBarTheme">@style/MyActionBar</item>
</style>
<style name="MyActionBar" parent="@style/ThemeOverlay.MaterialComponents.ActionBar">
<item name="android:background">#fff</item>
</style>
【解决方案2】:
我知道已经太晚了。
根据Material Component。您必须在您的 AppTheme 中添加:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
<!-- This will change ActionBar BackgroundColor to Black -->
<item name="colorSurface">#000000</item>
<!-- This will change ActionBar TextColor to White -->
<item name="colorOnSurface">#FFFFFF</item>
</style
注意:如果您从带有操作栏的模板创建项目,
检查你的文件:res/layout/app_bar_main.xml
确保删除:
中的android:background="?attr/colorPrimary" 如下图:
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" <<== MAKE SURE YOU DELETE THIS ONE LINE
app:popupTheme="@style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
否则,ActionBar BackgroundColor 将取决于:?attr/colorPrimary
【解决方案3】:
由于您使用的是Theme.MaterialComponents.Light 应用主题,ActionBar 背景颜色默认由 colorPrimary 属性定义。
只需使用 actionBarTheme 属性来覆盖背景颜色:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
<item name="actionBarTheme">@style/ThemeOverlay.ActionBar</item>
...
</style>
与:
<style name="ThemeOverlay.ActionBar" parent="">
<item name="colorPrimary">@color/mycolor</item>
</style>
您还可以在应用主题中使用 actionBarStyle 属性自定义背景颜色。
类似:
<style name="AppTheme" parent="Theme.MaterialComponents.*">
<item name="actionBarStyle">@style/Custom.ActionBar</item>
...
</style>
在这种情况下,您可以使用background 属性:
<style name="Custom.ActionBar" parent="Widget.MaterialComponents.Light.ActionBar.Solid">
<item name="background">@color/mycolor</item>
</style>