Как изменить цвет system bar android

First of all it's not a duplicate as in How to change the background color of android status bar How do I change the status bar color which should be same as in navigation bar. I want the status ...

Well, Izhar’s solution was OK but personally, I try to avoid code that looks as this:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//Do what you need for this SDK
};

But I don’t like to duplicate code either. In your answer I have to add a line of code like below in all Activities:

setStatusBarColor(findViewById(R.id.statusBarBackground),getResources().getColor(android.R.color.white));

So, I took Izhar’s solution and used XML to get the same result:
Create a layout for the StatusBar status_bar.xml

<View xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="@dimen/statusBarHeight"
     android:background="@color/primaryColorDark"
     android:elevation="@dimen/statusBarElevation">

Notice the height and elevation attributes, these will be set in values, values-v19, values-v21 further down.

Add this layout to your activities layout using include, main_activity.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/Black" >

<include layout="@layout/status_bar"/>
<include android:id="@+id/app_bar" layout="@layout/app_bar"/>
//The rest of your layout       
</RelativeLayout>

For the Toolbar, add top margin attribute:

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="@color/primaryColor"
app:theme="@style/MyCustomToolBarTheme"
app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
android:elevation="@dimen/toolbarElevation"
android:layout_marginTop="@dimen/appBarTopMargin"
android:textDirection="ltr"
android:layoutDirection="ltr">

</android.support.v7.widget.Toolbar>

In your appTheme style-v19.xml and styles-v21.xml, add the windowTranslucent attr:

styles-v19.xml, v21:

<resources>
<item name="android:windowTranslucentStatus">true</item>
</resources>

And finally, on your dimens, dimens-v19, dimens-v21, add the values for the Toolbar topMargin, and the height of the statusBarHeight:
dimens.xml for less than KitKat:

<resources>
<dimen name="toolbarElevation">4dp</dimen>
<dimen name="appBarTopMargin">0dp</dimen>
<dimen name="statusBarHeight">0dp</dimen>
</resources>

The status bar height is always 24dp
dimens-v19.xml for KitKat and above:

<resources>
<dimen name="statusBarHeight">24dp</dimen>
<dimen name="appBarTopMargin">24dp</dimen>
</resources>

dimens-v21.xml for Lolipop, just add the elevation if needed:

<resources>
<dimen name="statusBarElevation">4dp</dimen>
</resources>

This is the result for Jellybean KitKat and Lollipop:

enter image description here

A Status Bar in Android is an eye-catching part of the screen, all of the notification indication, battery life, time, connection strength, and plenty of things shows here. An Android user may look at a status bar multiple times while using an Android application. It is a very essential part of the design that the color of the status bar should follow the color combination of the layout. You can look out to many android apps on your phone and can see how they changed it according to its primary colors. There can be multiple ways for changing the status bar color but we are going to tell you about the best hand-picked two methods which you can use either in Java or Kotlin.

Method 1: Creating a New Theme

You can follow this method in apps that are built with Kotlin or Java. It will work in both.

Step 1: Open Android Studio and start a new project by selecting an empty activity. Give it a name of your choice, then select your language and API level. At last click on finish.

Step 2: Find an XML file called styles.xml by navigating res/values/styles.xml

Step 3: Find another XML file by navigating res/values/colors.xml, and also add that color here which you want to change for the status bar. 

Step 4: Now in the style.xml file, add the below code just before the </resources> tag and change the colors of it as your choice. ColorPrimaryDark is always going to be responsible for your status bar color. 

XML

<style name="DemoTheme" parent="Theme.AppCompat.Light.NoActionBar">

<item name="colorPrimary">@color/colorPrimary</item>

<item name="colorPrimaryDark">@color/colorOfStatusBar</item>

<item name="colorAccent">@color/colorAccent</item>

</style>

You can do the same with android:statusBarColor but it will work only in above API Level 21. ColorPrimaryDark for the status bar will also not support in API Level 19. By default in most of the API Levels, ColorPrimaryDark will be the default color for statusBarColor, So it is good to go with changing ColorPrimaryDark. 

Tip: You can create multiple themes and you can use them in any activity. In any theme, There is a set of colors that needs to be defined, you can also create new colors in the colors.xml file in the same directory and use it on the styles.xml file.

Step 6: Now go to the manifest/AndroidManifest.xml and here search the activity for which you want to apply that theme or change the color of the status bar. and add an attribute android:theme=”@style/DemoTheme”. 

That’s done! Check your application by running it on an emulator or a physical device.

Method 2: Using setStatusBarColor Method

This method can be only used in the above API Level 21. Officially status bar color is not supporting below API Level 21. Although, Here we added an if condition, because in case if you haven’t selected above or equal to API 21 then it will check the android API Version, and then it will execute the code. It will not change the color of the status bar is below API Level 21 but the rest code will work well.

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. Don’t forget to replace your desired color with colorName

Java

if (Build.VERSION.SDK_INT >= 21) {

            Window window = this.getWindow();

            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

            window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimaryDark));

        }

Kotlin

if (Build.VERSION.SDK_INT >= 21) {

            val window = this.window

            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)

            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)

            window.statusBarColor = this.resources.getColor(R.color.colorPrimaryDark)

        }

Step 4: Try running your application on an android emulator or a physical device. See the changes.

Output for both the methods will be the same:

I was wondering if it’s possible to change the statusbar icons colour (not the statusbar colour, colorPrimaryDark)
enter image description here
Let’s say I want this statusbar with:
<item name="colorPrimaryDark">@android:color/white</item>

and the icons in black, is it possible?

Thanks.

EDIT:

New in the M developer preview: windowLightStatusBar. Flipping this on
in your theme tells the system to use a dark foreground, useful for
lighter colored status bars. Note the M preview seems to have a bug
where notification icons remain white, while system status icons
correctly change to semitransparent black.

from: Roman Nurik Google+ post
enter image description here

asked May 6, 2015 at 11:48

GuilhE's user avatar

GuilhEGuilhE

11.5k16 gold badges74 silver badges112 bronze badges

Yes it’s possible to change it to gray (no custom colors) but this only works from API 23 and above you only need to add this in your values-v23/styles.xml

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

enter image description here

answered Nov 24, 2015 at 13:23

eOnOe's user avatar

eOnOeeOnOe

2,7532 gold badges12 silver badges7 bronze badges

1

@eOnOe has answered how we can change status bar tint through xml. But we can also change it dynamically in code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    View decor = getWindow().getDecorView();
    if (shouldChangeStatusBarTintToDark) {
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    } else {
        // We want to change tint color to white again.
        // You can also record the flags in advance so that you can turn UI back completely if
        // you have set other flags before, such as translucent or full screen.
        decor.setSystemUiVisibility(0);
    }
}

answered Jun 8, 2016 at 6:06

ywwynm's user avatar

ywwynmywwynm

11.4k7 gold badges36 silver badges53 bronze badges

5

if you have API level smaller than 23 than you must use it this way.
it worked for me declare this under v21/style.

<item name="colorPrimaryDark" tools:targetApi="23">@color/colorPrimary</item>
        <item name="android:windowLightStatusBar" tools:targetApi="23">true</item>

answered Dec 30, 2016 at 4:45

Ritesh's user avatar

RiteshRitesh

8569 silver badges14 bronze badges

3

Not since Lollipop. Starting with Android 5.0, the guidelines say:

Notification icons must be entirely white.

Even if they’re not, the system will only consider the alpha channel of your icon, rendering them white

Workaround

The only way to have a coloured icon on Lollipop is to lower your targetSdkVersion to values <21, but I think you would do better to follow the guidelines and use white icons only.

If you still however decide you want colored icons, you could use the DrawableCompat.setTint method from the new v4 support library.

answered May 6, 2015 at 11:52

Kuba Spatny's user avatar

Kuba SpatnyKuba Spatny

26.4k9 gold badges39 silver badges63 bronze badges

8

SystemUiVisibility flags are deprecated. Use WindowInsetsController instead

the code below sets the color of icons to black (for the light statusbar)

//icon color -> black  
activity.getWindow().getDecorView().getWindowInsetsController().setSystemBarsAppearance(APPEARANCE_LIGHT_STATUS_BARS, APPEARANCE_LIGHT_STATUS_BARS);

and the code below clears it(i.e. turns icon color to white for dark statusbar):

//icon color -> white
activity.getWindow().getDecorView().getWindowInsetsController().setSystemBarsAppearance(0, APPEARANCE_LIGHT_STATUS_BARS);

link to docs :
https://developer.android.com/reference/android/view/WindowInsetsController#setSystemBarsAppearance(int,%20int)

answered Mar 23, 2021 at 19:44

Mark Andrew's user avatar

5

Setting windowLightStatusBar to true not works with Mi phones, some Meizu phones, Blackview phones, WileyFox etc.
I’ve found such hack for Mi and Meizu devices. This is not a comprehensive solution of this perfomance problem, but maybe it would be useful to somebody.

And I think, it would be better to tell your customer that coloring status bar (for example) white — is not a good idea. instead of using different hacks it would be better to define appropriate colorPrimaryDark according to the guidelines

answered Jan 22, 2018 at 9:40

Jackky777's user avatar

Jackky777Jackky777

64412 silver badges19 bronze badges

You can do it programmatically with retaining all other system UI visibility flags.

public static void changeStatusBarContrastStyle(Window window, Boolean lightIcons) {
     View decorView = window.getDecorView();
     if (lightIcons) {
         // Draw light icons on a dark background color
         decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
     } else {
         // Draw dark icons on a light background color
         decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
     }
 }

answered Oct 8, 2021 at 6:27

Mahmoud's user avatar

MahmoudMahmoud

2,5351 gold badge28 silver badges30 bronze badges

1

This is for all those who want to change their application’s Notification small icon color can use this setColor method of NotificationCompat.Builder

Example:

val builder = NotificationCompat.Builder(this, "whatever_channel_id")
        **.setSmallIcon(R.drawable.ic_notification) //set icon for notification**
        .setColor(ContextCompat.getColor(this, R.color.pink))
        .setContentTitle("Notification Title")
        .setContentText("Notification Message!")

answered Mar 4, 2021 at 15:51

Kishan Solanki's user avatar

Kishan SolankiKishan Solanki

13.2k4 gold badges80 silver badges79 bronze badges

I used two line of code for different status bar color

1st: If status bar color is white then use this line of code to visible the status bar icon:

  pingAct.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
  
      

2nd: If you use dark color then use this line of code to make visible the status bar icon:

 pingAct.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

               

answered Oct 12, 2022 at 15:48

Pir Fahim Shah's user avatar

Pir Fahim ShahPir Fahim Shah

10.3k1 gold badge79 silver badges79 bronze badges

in kotlin you can use following lines

    val window = this.window
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
    window.statusBarColor = ContextCompat.getColor(this, R.color.white)
    WindowCompat.getInsetsController(window, window.decorView).apply {
        isAppearanceLightStatusBars = true
    }

answered Jan 24 at 11:39

Swapnil's user avatar

Yes you can change it. but in api 22 and above, using NotificationCompat.Builder and setColorized(true) :

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, context.getPackageName())
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(icon, level)
                .setLargeIcon(largeIcon)
                .setContentIntent(intent)
                .setColorized(true)
                .setDefaults(0)
                .setCategory(Notification.CATEGORY_SERVICE)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

answered Nov 16, 2018 at 13:55

hadi seylani's user avatar

2

I was wondering if it’s possible to change the statusbar icons colour (not the statusbar colour, colorPrimaryDark)
enter image description here
Let’s say I want this statusbar with:
<item name="colorPrimaryDark">@android:color/white</item>

and the icons in black, is it possible?

Thanks.

EDIT:

New in the M developer preview: windowLightStatusBar. Flipping this on
in your theme tells the system to use a dark foreground, useful for
lighter colored status bars. Note the M preview seems to have a bug
where notification icons remain white, while system status icons
correctly change to semitransparent black.

from: Roman Nurik Google+ post
enter image description here

asked May 6, 2015 at 11:48

GuilhE's user avatar

GuilhEGuilhE

11.5k16 gold badges74 silver badges112 bronze badges

Yes it’s possible to change it to gray (no custom colors) but this only works from API 23 and above you only need to add this in your values-v23/styles.xml

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

enter image description here

answered Nov 24, 2015 at 13:23

eOnOe's user avatar

eOnOeeOnOe

2,7532 gold badges12 silver badges7 bronze badges

1

@eOnOe has answered how we can change status bar tint through xml. But we can also change it dynamically in code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    View decor = getWindow().getDecorView();
    if (shouldChangeStatusBarTintToDark) {
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    } else {
        // We want to change tint color to white again.
        // You can also record the flags in advance so that you can turn UI back completely if
        // you have set other flags before, such as translucent or full screen.
        decor.setSystemUiVisibility(0);
    }
}

answered Jun 8, 2016 at 6:06

ywwynm's user avatar

ywwynmywwynm

11.4k7 gold badges36 silver badges53 bronze badges

5

if you have API level smaller than 23 than you must use it this way.
it worked for me declare this under v21/style.

<item name="colorPrimaryDark" tools:targetApi="23">@color/colorPrimary</item>
        <item name="android:windowLightStatusBar" tools:targetApi="23">true</item>

answered Dec 30, 2016 at 4:45

Ritesh's user avatar

RiteshRitesh

8569 silver badges14 bronze badges

3

Not since Lollipop. Starting with Android 5.0, the guidelines say:

Notification icons must be entirely white.

Even if they’re not, the system will only consider the alpha channel of your icon, rendering them white

Workaround

The only way to have a coloured icon on Lollipop is to lower your targetSdkVersion to values <21, but I think you would do better to follow the guidelines and use white icons only.

If you still however decide you want colored icons, you could use the DrawableCompat.setTint method from the new v4 support library.

answered May 6, 2015 at 11:52

Kuba Spatny's user avatar

Kuba SpatnyKuba Spatny

26.4k9 gold badges39 silver badges63 bronze badges

8

SystemUiVisibility flags are deprecated. Use WindowInsetsController instead

the code below sets the color of icons to black (for the light statusbar)

//icon color -> black  
activity.getWindow().getDecorView().getWindowInsetsController().setSystemBarsAppearance(APPEARANCE_LIGHT_STATUS_BARS, APPEARANCE_LIGHT_STATUS_BARS);

and the code below clears it(i.e. turns icon color to white for dark statusbar):

//icon color -> white
activity.getWindow().getDecorView().getWindowInsetsController().setSystemBarsAppearance(0, APPEARANCE_LIGHT_STATUS_BARS);

link to docs :
https://developer.android.com/reference/android/view/WindowInsetsController#setSystemBarsAppearance(int,%20int)

answered Mar 23, 2021 at 19:44

Mark Andrew's user avatar

5

Setting windowLightStatusBar to true not works with Mi phones, some Meizu phones, Blackview phones, WileyFox etc.
I’ve found such hack for Mi and Meizu devices. This is not a comprehensive solution of this perfomance problem, but maybe it would be useful to somebody.

And I think, it would be better to tell your customer that coloring status bar (for example) white — is not a good idea. instead of using different hacks it would be better to define appropriate colorPrimaryDark according to the guidelines

answered Jan 22, 2018 at 9:40

Jackky777's user avatar

Jackky777Jackky777

64412 silver badges19 bronze badges

You can do it programmatically with retaining all other system UI visibility flags.

public static void changeStatusBarContrastStyle(Window window, Boolean lightIcons) {
     View decorView = window.getDecorView();
     if (lightIcons) {
         // Draw light icons on a dark background color
         decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
     } else {
         // Draw dark icons on a light background color
         decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
     }
 }

answered Oct 8, 2021 at 6:27

Mahmoud's user avatar

MahmoudMahmoud

2,5351 gold badge28 silver badges30 bronze badges

1

This is for all those who want to change their application’s Notification small icon color can use this setColor method of NotificationCompat.Builder

Example:

val builder = NotificationCompat.Builder(this, "whatever_channel_id")
        **.setSmallIcon(R.drawable.ic_notification) //set icon for notification**
        .setColor(ContextCompat.getColor(this, R.color.pink))
        .setContentTitle("Notification Title")
        .setContentText("Notification Message!")

answered Mar 4, 2021 at 15:51

Kishan Solanki's user avatar

Kishan SolankiKishan Solanki

13.2k4 gold badges80 silver badges79 bronze badges

I used two line of code for different status bar color

1st: If status bar color is white then use this line of code to visible the status bar icon:

  pingAct.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
  
      

2nd: If you use dark color then use this line of code to make visible the status bar icon:

 pingAct.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

               

answered Oct 12, 2022 at 15:48

Pir Fahim Shah's user avatar

Pir Fahim ShahPir Fahim Shah

10.3k1 gold badge79 silver badges79 bronze badges

in kotlin you can use following lines

    val window = this.window
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
    window.statusBarColor = ContextCompat.getColor(this, R.color.white)
    WindowCompat.getInsetsController(window, window.decorView).apply {
        isAppearanceLightStatusBars = true
    }

answered Jan 24 at 11:39

Swapnil's user avatar

Yes you can change it. but in api 22 and above, using NotificationCompat.Builder and setColorized(true) :

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, context.getPackageName())
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(icon, level)
                .setLargeIcon(largeIcon)
                .setContentIntent(intent)
                .setColorized(true)
                .setDefaults(0)
                .setCategory(Notification.CATEGORY_SERVICE)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

answered Nov 16, 2018 at 13:55

hadi seylani's user avatar

2

Over the past few months, I have been attempting to figure out the best ways to implement a light theme and dark theme in my Hanselman.Forms app. Working closely with my friend Kym Phillpotts we came up with a very nice theme changer for Xamarin.Forms, that allowed us to change all of the colors dynamically. The result is a very nice looking application that allows the users to pick their theme or use system defaults.

Picking themes in Hanselman.Forms between light and dark theme

One thing that bugged me in the original implementation for Android, was the status bar color that was a single dark blue color. Modern apps will set the status bar to match the background color when toggling between light and dark. Since we are allowing the user to set the theme, we must also set the color of the status bar.

This can be accomplished with the following code:

public void SetStatusBarColor(System.Drawing.Color color, bool darkStatusBarTint)
{
    if (Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.Lollipop)
        return;
        
    var activity = Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity;
    var window = activity.Window;
    window.AddFlags(Android.Views.WindowManagerFlags.DrawsSystemBarBackgrounds);
    window.ClearFlags(Android.Views.WindowManagerFlags.TranslucentStatus);
    window.SetStatusBarColor(color.ToPlatformColor());
}

This uses my Current Activity Plugin to get the Window of the app, and also Xamarin.Essentials Color Converters to set the color to light or dark.

Screenshot of the status bar in dark theme with matching color

This works really great unless I set it to a light color where the icon colors remain white.

Screenshot of the status bar in light them where icons are white too

We can also control this with the following code:

if(Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.M)
{
    var flag = (Android.Views.StatusBarVisibility)Android.Views.SystemUiFlags.LightStatusBar;
    window.DecorView.SystemUiVisibility = darkStatusBarTint ? flag : 0;
}

Now it looks beautiful, and we are in full control!

Screenshot of the status bar in light them where icons are dark color

Get the code

All of the source code for Hanselman.Forms can be found on GitHub and you can watch me code live on Twitch. I also archive all the videos on my YouTube channel.

Copyright © James Montemagno 2023 All rights reserved. Privacy Policy

Proudly published with Ghost. Branding and design by Cinder Design Co.

Changing the Android status bar color is very easy in Android Studio. Set color on android:colorPrimaryDark the attribute of the style you’re using for your app in styles.xml.

Android 5.0 Lollipop introduced Material Design theme which automatically colors the status bar based on the colorPrimaryDark value of the theme.

Code

<color name="colorPrimaryDark">#2196F3</color>

On API level 21+ you can also use the Window.setStatusBarColor() method from code.

You can use this simple code in Kotlin:

window.statusBarColor = ContextCompat.getColor(this, R.color.colorName)

Let’s build an Android status bar color change application

Step 1. Create an android project in the android studio (Follow this tutorial: Android First Program in Android Studio).

Step 2. Open the color.xml file.

Step 3. Add your color in the color.xml file.

You can add status bar color in 2 ways, First clicking on left side color box-> it will open a color selector.

Another way direct write a color hex code.

Android status bar color change

Step 4. Now Run the application, in an emulator or on your Android device.

Output screenshot Android android:colorPrimaryDark example:

Android colorPrimaryDark example output

Download Link and Source of Android status bar color change code in Github

https://github.com/EyeHunts/AndroidStatusBarColor

Q: How to change Action Bar and Status Bar color in Activity?

Answer: If you want to change the color of my action bar and status bar programmatically only on one activity. Then use this Java(for Kotlin you just copy past and chose change to Kotlin) code.

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        changeColor(R.color.red);
    }


    public void changeColor(int resourseColor) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(ContextCompat.getColor(getApplicationContext(), resourseColor));
        }

        ActionBar bar = getSupportActionBar();
        bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(resourseColor)));

    }

}

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in Android Studio 3.3.2. Tested on Android 9 ( Android-P), compile SDK version API 28: Android 9.0 (Pie)
MinSdkVersion=25″
TargetSdkVersion=28″Coding in Kotlin

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.

status bar color changeChanging the color of the status bar is available only for devices with Android Lollipop(API 21) and higher.
Therefore we would have to add a line of code that would check if the android version is at lease 21 or not and then try to change the color of the status bar.

Color of the status bar can be changed both programatically(using Java) and through XML.

In this article I would show how to do it in a way such that your app can still run on lower devices without crashing but on devices with sdk 21 and higher it will change the color of the status bar.

  • Using JAVA:
    Just add the following snippet of code to the OnCreate Method of the Activity whose status bar you want to change:

    //changing statusbar color
            if (android.os.Build.VERSION.SDK_INT >= 21) {
                Window window = this.getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.setStatusBarColor(this.getResources().getColor(R.color.your_color));
            }
    

    Such that the Activity looks like:
    status bar color change 1

    Note: There is a flaw in this method. That is, you need to add this code to all the Activities of your App which is quite tiresome if you have a lot of Activities.

  • Using XML:
    Another way you can change the color of the status bar is through styles.xml.
    status bar color change 2

The advantage of this method is that you don’t need to set the color of status bar for every activity.
However, some designers may want different colors for different activities in which case the first method would be useful.

Well, that’s it. Pretty easy Right?!
If you have any questions or doubts just drop them in the comments section down below.

Manas Sharma

Ph.D. researcher at Friedrich-Schiller University Jena, Germany. I’m a physicist specializing in computational material science. I write efficient codes for simulating light-matter interactions at atomic scales. I like to develop Physics, DFT, and Machine Learning related apps and software from time to time. Can code in most of the popular languages. I like to share my knowledge in Physics and applications using this Blog and a YouTube channel.

[wpedon id=»7041″ align=»center»]

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить цвет svg через css при наведении
  • Как изменить цвет svg через css img
  • Как изменить цвет svg через css background
  • Как изменить цвет svg при hover
  • Как изменить цвет svg картинки при наведении css

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии