androiduser-interfaceandroid-6.0-marshmallowandroid-statusbar

Android M Light and Dark status bar programmatically - how to make it dark again?


In the Android M we have ability to make status bar icons dark. To do that we can specify attribute in the theme's xml:

<item name="android:windowLightStatusBar">true</item>

OR we cat set it at runtime with this code:

View someView = findViewById(R.id.some_view);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    someView.setSystemUiVisibility(someView.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}

And it actually works fine. But question is how to properly set a status bar mode to dark at runtime?

I already tried these variants:

// Makes status bar mode dark, but also hides it along with all navigation views. 
someView.setSystemUiVisibility(someView.getSystemUiVisibility() | ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

// Does nothing 
someView.setSystemUiVisibility(someView.getSystemUiVisibility() & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

// Also does nothing 
someView.setSystemUiVisibility(someView.getSystemUiVisibility() ^ View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

So how it can be done the right way?


Solution

  • The solution posted by @Aracem is valid but, doesn't work if you try change also the background color of the status bar. In my case I do it in the following way.

    To enable windowLightStatusBar(programatically,inside a Utils class for example):

     public static void setLightStatusBar(View view,Activity activity){
    
    
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    
                    int flags = view.getSystemUiVisibility();
                    flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                    view.setSystemUiVisibility(flags);
                    activity.getWindow().setStatusBarColor(Color.WHITE); 
                }
    }
    

    To restore to StatusBar to the previous state:

      public static void clearLightStatusBar(Activity activity) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                Window window = activity.getWindow();
                window.setStatusBarColor(ContextCompat
                     .getColor(activity,R.color.colorPrimaryDark)); 
            }
        }
    

    Restoring the color of the status bar is enough, it restores also the icons colors. VERY IMPORTANT: The restore operation will not occur until the view used in setLightStatusBar(View view..) dissapears(that is, view.getVisibility()==GONE|INVISIBLE) from the screen.