Setting background color of android actionbar

2019-05-20 19:20发布

问题:

I am operating with the compatibility library v7.

I am just trying to set the color of my actionbar (for Android 2.1 and above - though I run Android 4.4.2) to a solid color.

However the color does not change. It remains the same.

I have also tried creating a solid drawable with the color but that also does not change.

Finally I tested if I could change the backgroudn of my layout and I could - it must be something about the actionbar background which I'm not getting.

Here is the code:

    <?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="CustomActionBarTheme"
           parent="@style/Theme.AppCompat.Light.DarkActionBar">

        <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/MyActionBar</item>
    </style>

    <style name="MyActionBar" parent="@style/Widget.AppCompat.ActionBar">

         <item name="android:background">#0000ff</item>  

    </style>
</resources>

回答1:

This seems to work for me. Try to use a resource instead of a raw value.

<style name="app_theme" parent="@android:style/Theme.Holo">
    <item name="android:actionBarStyle">@style/app_action_bar</item>
</style>

<style name="app_action_bar" parent="@android:style/Widget.Holo.ActionBar">
    <item name="android:background">@color/google_lightest_gray</item>
    <item name="android:icon">@android:color/transparent</item>
    <item name="android:windowActionBarOverlay">false</item>
</style>


回答2:

use getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#808080"))); in Activity extends SherlockActivity or the color as your wish :)



回答3:

You can use:

getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.color.colorname));


回答4:

use the following code getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_bg_color.xml));

actionbar_bg_color.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
      <solid android:color="@color/actionbar_bg"/>  <!-- set desired #0000ff color in color.xml
 you can use here solid color as well as gradient -->
 </shape>

hope this help you



回答5:

I solved it by:

  • Properly installing the support-v7-appcompat library.My mistake.
  • Shifting the styling to the res/values/styles.xml files for each version, i.e. one for backwards compatibility and one for values-v11.

I don't know why I couldnt get the result I wanted within themes.xml.

If anyone has an answer I'd be grateful