Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change status bar color without losing transparency

I know I can use colorPrimary to determine the color of Toolbar, and colorPrimaryDark to determine the color of Status bar.

I'm using the following theme

<!-- Base application theme. -->
<style name="Theme.Noteplus.Base.Brown" parent="Theme.AppCompat.Light.DarkActionBar">

    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimaryLight</item>
    <item name="colorPrimaryDark">#ff0000</item>

    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>

One of the interesting attribute is, when I slide out the navigation menu, the status bar becomes transparent automatically.


During run-time, sometime I would like to change the color of status bar.

setTitle("Recycler bin");
toolbar.setBackgroundColor(Color.BLUE);
getWindow().setStatusBarColor(Color.parseColor("#5694FF"));

It will looks as follow

Unfortunately, calling setStatusBarColor, will also loss the transparency attribute of status bar, when we slide out the navigation menu.

May I know, how to change status bar color during run-time, without lossing its transparency attribute? For my case, after I changing the status bar to blue during run-time, when I slide out navigation drawer, I wish to see status bar transparency attribute being retained.


Update

I had tried

private void setStatusBarColor(int color) {
    if (Build.VERSION.SDK_INT >= 21) {
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(color);
    }
}

It doesn't help to provide transparency attribute when the navigation drawer slides out.

like image 306
Cheok Yan Cheng Avatar asked May 06 '18 15:05

Cheok Yan Cheng


1 Answers

You are using a DrawerLayout. That means, that instead of using Window#setStatusBarColor(int) you should be using one of DrawerLayout#setStatusBarBackground() overloads.

The equivalent of your code is following:


    ColorDrawable colorDrawable = new ColorDrawable(0xFF5694FF);
    drawerLayout.setStatusBarBackground(colorDrawable);

I've applied minor changes to the template app that can be created with Android Studio wizard:

enter image description here

like image 65
azizbekian Avatar answered Sep 20 '22 00:09

azizbekian