How to change the color of the android actionbar w

2019-09-20 06:53发布

问题:

I want to change the color of my actionbar but I'm no good at making image resources so I want to know if there is anyway it is possible to do that without images. like setting a color to some property or something? I surfed a lot but there are too many confusing answers and I can't figure out which one to use.
I am developing for sdk above 8 so I'm using support libraries. Please help.

回答1:

You could have easily found out the answer here. Or you can click here to create image resources very easily. But anyway, this is how you do it.
first of all, define a color you want for your actionbar in "colors.xml" in the "values" folder of your project like this:

    <color name="customColor">#f1f1f1</color>

Then create a new .xml file in your drawable folder with the name say "actionbar_drawable.xml". It has to be a "shape" drawable.

drawable\actionbar_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >    
    <solid 
        android:color="@color/customColor"/>    
</shape>

Now create "themes.xml" in "values" folder with the following code:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">

    <style name="CustomActionBar" parent="@style/Theme.AppCompat.Light">
       <item name="android:actionBarStyle" tools:targetApi="11">@style/CustomBar</item>
    <!-- Support library compatibility -->
       <item name="actionBarStyle">@style/CustomBar</item>         
    </style>

    <style name="CustomBar"
         parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
       <item name="android:background">@drawable/actionbar_drawable</item>
    <!-- Support library compatibility -->
       <item name="background">@drawable/actionbar_drawable</item>
    </style>
</resources>

Then in your manifest file, set the theme for your activity like this:

android:theme="@style/CustomActionBar"  

That's all. Now you won't have to make any image resource. Hope it's helpful to you.



回答2:

Generate what ever theme you want from Android Action Bar Style Generator

Copy all the files it generates to the respective folders in res folder and VOILA.. ;)



回答3:

activity.getSupportActionBar().setBackgroundDrawable(new ColorDrawable(activity.getResources().getColor(R.color.my_color)));