11

I'm wondering how to change the StatusBar color dependent on the current active Fragment (on 5.0 Lollipop). Currently, I change the ActionBar color dependent on the Fragment I am in, but now I want the StatusBar color to change as well - in order to look nice on Lollipop devices.

I've tried using setStyle to programmatically change the theme depending on the fragment, but it doesn't seem to be changing the status bar color.

Any ideas would be appreciated!

user3634770
  • 231
  • 1
  • 3
  • 7
  • Can you show the code that you've tried? – Alex K Nov 04 '14 at 19:11
  • It's a little messy, but essentially I have a FragmentData object which stores the style (amongst other things) I want for each fragment. Whenever the fragment changes I setStyle to the mStyle field I have in that object. Just a side note: This is working to change the actionbar color, it's just that the statusbar color doesn't seem to be set. – user3634770 Nov 04 '14 at 19:14
  • Yeah of course. This isn't just for me - it's for anybody reading the question. – Alex K Nov 04 '14 at 19:18
  • Right, heres a chunk of the code Im using right now: `if (fragmentData != null) { updateActionBarForFragment(fragmentData); mStyle = fragmentData.getStyle(); } setTheme(mStyle);` – user3634770 Nov 04 '14 at 20:36
  • possible duplicate of [Change status bar color with AppCompat ActionBarActivity](http://stackoverflow.com/questions/26702000/change-status-bar-color-with-appcompat-actionbaractivity) – matiash Dec 22 '14 at 20:15

1 Answers1

19

Have you tried to change the color of the status bar using Window.setStatusBarColor? For example, you can do the following to change the status bar color to red programmatically.

getWindow().setStatusBarColor(Color.RED);

The documentation of setStatusBarColor can be found here. You can also read the documentation on how to Customize the Status Bar.

Note: This method only works at Lollipop or above.

If you are seeing an unexpected color, make sure the integer value you are passing is a color integer and not a resource ID.

getWindow().setStatusBarColor(getResources().getColor(R.color.custom_color)); // RIGHT
getWindow().setStatusBarColor(R.color.custom_color); // WRONG
ztan
  • 6,861
  • 2
  • 24
  • 44
  • So, `getWindow().setStatusBarColor(...)` works to change the status bar color, but its not setting the right color. So for example, when I set the status bar color to orange, it comes out as purple. Any idea what's going on? – user3634770 Nov 07 '14 at 19:37
  • is there a way to do the same in android 4.4 ? – Amin Keshavarzian Feb 26 '15 at 09:12
  • @AminKeshavarzian You have to use app compact, and do `@color/BackgroundColor' in your style or theme xml to support android 4.4 devices. – ztan Feb 26 '15 at 16:26
  • Changing status bar's color programmatically is just possible in API 21 ? I want to change the color programmatically in API less than 21 , Is it possible ? – Morteza Soleimani Mar 30 '15 at 07:04