简体   繁体   中英

Android: Setting Action Bar Background Color

I know there are plenty of questions about this but I can't figure out what's wrong with my styles.

This is in my manifest:

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

And in values\\styles.xml, I have (EDIT, as per answers below, I moved the color to a resource).

<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
  <item name="android:actionBarStyle">@style/MyActionBar</item>
</style>

<!-- ActionBar styles -->
  <style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:background">@color/white</item>
</style>
</resources>

And added a res/values/color.xml file, which contains:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="white">#ffffff</color>
</resources>

If I change the first style's line to:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

This does reflect and turns the bar dark.

Why is my action bar not getting set to white?

Edit 1: If it helps, my minSdkVersion is 16 and my targetSdkVersion is 21.

<!-- ActionBar styles -->
<style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:background">#FFFFFF</item> 
</style>

the android:background attribute ONLY takes reference value, you are inserting raw color value, so it is ignored. Create a color resource instead and point to that resource like this <item name="android:background">@color/white</item>

I thought this was what you need:

<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/app_color_Primary</item>
    <item name="colorPrimaryDark">@color/app_color_primary_dark</item>
    <item name="colorAccent">@color/app_color_accent</item>
    ...
</style>

You can set the background color of your ActionBar dynamically as well. Example:

final ActionBar actionBar = getActionBar();
final int actionBarColor = getResources().getColor(R.color.green);
actionBar.setBackgroundDrawable(new ColorDrawable(actionBarColor));

Note: I have already created a new file called color.xml in values/ and defined a color value for tag 'green' like:

<color name="green">#8CBE41</color>

Hope it will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM