![](/img/trans.png)
[英]How do I change the background color of the ActionBar of an ActionBarActivity using XML?
[英]How do I change the background color of the ActionBar in the new MaterialComponents
我正在使用新的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 的背景顏色
我知道這個問題,但它已經過時並且不使用MaterialComponents
我不想將 Toolbar 添加到每個屏幕只是為了更改背景顏色。
您需要根據背景顏色使用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>
我知道已經太晚了。
根據材料成分。 您必須在 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 確保刪除: <androidx.appcompat.widget.Toolbar /> 中的 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
由於您使用的是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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.