3

I have an app which uses android.support.v7.widget.Toolbar. Every section of the app is a Fragment accessed through a support.v4.widget.DrawerLayout

I need to change the Toolbar color depending on which section is shown (client particular needs).

I defined some colors in the colors.xml so I can make something like:

changeToolbarColor(R.color.section_one);

/**/

private void changeToolbarColor(int color_res_id){
    Integer colorTo = getResources().getColor(color_res_id);
    toolbar.setBackgroundColor(colorTo);
}

The problem is, once I do this, every view using the primaryColor (the original primary color from the toolbar) now shows up using the new color of the Toolbar.

So if my Toolbar was green and I change it to red, now everything using the old green uses red instead.

I suspect, that the change of the Toolbars background changes the primaryColor definition itself (which makes no sense to me). Because I have no other idea of how unrelated elements in unrelated activities start using the same color.

Is this a bug? Anyone with this problem? Any workarounds available?

Thanks for your help.

Eloi Navarro
  • 1,435
  • 1
  • 14
  • 26
  • I guess (but not sure) that you should create different themes and recreate the toolbar depending on the selection, but probably this is not the best behavior – basteez Jun 20 '15 at 14:40
  • I thought about it @tizionario and I agree with you. It seems not the best approach. It looks like Toolbar's color has to be easy to change. But apparently it isn't, maybe using `Palette` or any other approach? But I can't think of a propper way of doing it right now. – Eloi Navarro Jun 21 '15 at 00:22

1 Answers1

1

First of all themes are immutable, so it's not possible to change the primary color of the app.

And try using getSupportActionBar().setBackgroundDrawable().

I guess it's something else which is causing the issue. Can you post more code ?

Akshay Chordiya
  • 4,761
  • 3
  • 40
  • 52
  • Thx @Aky for the answer, but it's not the `theme` I'm trying to change but the `Toolbar` color, which is defined by the value put on the `primaryColor` (in `themes.xml`) I mean, if the primary color is red, I want it to stay red, so every other element stays red. But the toolbar, I may want it to be green, blue or whatever I need. But once I change toolbar's color, every other element using the `primaryColor` color changes aswell. – Eloi Navarro Jun 21 '15 at 00:17
  • @EloiNavarro Ohhkay, But did you try `getSupportActionBar().setBackgroundDrawable()` ? – Akshay Chordiya Jun 21 '15 at 12:55
  • I must admit it, I wasn't sure this was going to show any difference at all. But indeed, it solved my issue. Thank you very much! – Eloi Navarro Jul 07 '15 at 11:42
  • @EloiNavarro I'm glad it helped – Akshay Chordiya Jul 08 '15 at 11:50