Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Background Color of AppCompat Action Bar

I am in a fragment and I want to change the actionbar color and view background color when the user clicks on a button. The code I currently have below causes the action bar to go gray no matter what color the user chooses.

private void changeColor( int colorId ) {
    ActionBar actionBar =  ((ActionBarActivity )getActivity()).getSupportActionBar();
    actionBar.setBackgroundDrawable( new ColorDrawable( colorId ) );
    this.getView().setBackgroundColor( getResources().getColor( colorId ) );
}

I have the actionbar themed to be blue in my styles.xml not sure if that has any effect. If you have any suggestion please let me know.

Thanks, Nathan

Solution: Had to change:

actionBar.setBackgroundDrawable( new ColorDrawable( colorId ) );

To:

actionBar.setBackgroundDrawable( new ColorDrawable( getResources().getColor( colorId ) ) );
like image 839
Nath5 Avatar asked Sep 27 '14 02:09

Nath5


People also ask

How can I change action bar title color?

in your style. xml in values folder this will change your action bar color.. Replace #666666 with your selected color code for title background color and replace #000000 for your title text color.

How do I change the color of my status bar?

Step 1: After opening the android studio and creating a new project with an empty activity. Step 2: Navigate to res/values/colors. xml, and add a color that you want to change for the status bar. Step 3: In your MainActivity, add this code in your onCreate method.


1 Answers

If i understand your question correctly that you want to change the color base on user intervention, try this instead.

public void setActionBarColor(int parsedColor){
    ActionBar mActionBar = getSupportActionBar();
    mActionBar.setBackgroundDrawable(new ColorDrawable(parsedColor));
    mActionBar.setDisplayShowTitleEnabled(false);
    mActionBar.setDisplayShowTitleEnabled(true);
}

using this in a fragment

// check if instance of activity is MyActivity just an example
MyActivity mA = ((MyActivity)getActivity());
mA.setActionBarColor(Color.parseColor("#FFA2C13E"));

hope it helps :)

PS: im using ActionBarActivity

like image 186
Spurdow Avatar answered Oct 01 '22 02:10

Spurdow