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

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

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.

Android studio kotlin java change status bar color


Hello Today we learn how to change status bar background color in android studio.

What is status bar ?

In android phones , status bar contains notifications and system icons. As you can see in above image that area is status bar.

Here we will change background color through xml so it will be work with both java and kotlin. You can change status bar color by many ways but here we are using very simple way to do this. So please follow below steps:-

Please open your project folder and navigate to app/src/main/res/values/styles.xml or just search styles.xml file and then add below line in it

<item name="android:statusBarColor">#333</item>

Here we are using dark color code #333 but you can use any color code according to you and it will be good if you use color according to your app theme.

So after adding this code your code will be look like this

<resources>
    <!-- Base application theme. -->    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="android:statusBarColor">#333</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

After the above process, please click on build and check it will work. Thanks for reading :)

Popular posts from this blog

  Today we learn how to use scss and generate css using node  or Run and compile sass scss file to css using node   So please follow simple  steps :-   Today we will create a project that can read scss file and generates css with it  Note: Make sure you have installed node in your system. If you want to help to install node js based on your system then check our other tutorial or check node js official website. Now create a blank folder and open  terminal(linux) or cmd(windows) and navigate to your current project folder by using cd command Now run below command npm init after enter it will ask you some package info that you can fill according to you or just keep enter until it finished. The above command will generate package.json file Now  we will install npm module that will convert our scss to css Run below command: npm install node-sass So we have installed node-sass package . Now open package.json file in your editor and add below code into it into

Solution for expo is not recognized as an internal or external command,operable program or batch file in Windows 10 Sometimes expo will not work globally mostly in windows 10, If you are facing same issue then follow the below Steps 1) Click on windows button and search for  » Environment variables»  and click on «Edit the system environment variables» 2) Now you will see a popup like below screen. Then you need to click on Environment Variables. (Please see highlight part in below image)     3)Then click on new button that i have highlighted in below image 4. Then a popup will open and you need to fill details like below mentioned Variable Name :Path Variable Value: %USERPROFILE%AppDataRoamingnpm Here we are creating a new path variable and passing location of npm.   Now Click on OK and close all the terminal windows and open new CMD or terminal and type Expo . Great now you can access expo from any loc

jQuery Datatable add date range filter Datatable is most useful jQuery plugin that helps to make our html tables more powerful and give powers to user to filter , search, sort, pagination etc, But Data table provides a common filter only and yes we can customize and add filter for each column, but still sometimes we need an advance filter like show results only between a date range, So today we will learn how to create a minimum and maximum date range fields and show date picker on it, and user can fill dates by selecting dates and data table will auto filter records based on it. Keep follow below steps :- I am using Bootstrap if you want to use any other framework then you can use. Create a new index.php file  and paste below code in it, i have used all required CDN like bootstrap, datatable, datepicker etc. <!DOCTYPE html> <html> <head>     <title>Datatable Date Range Filter Example</title>     <link rel=»stylesheet» href=»https://maxcd

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.

7 ответов

Вы можете изменить его, установив android:statusBarColor или android:colorPrimaryDark стиля, который вы используете для своего приложения, в styles.xml.

(android:statusBarColor наследует значение android:colorPrimaryDark по умолчанию)

Например (поскольку здесь мы используем тему AppCompat, пространство имен android опущено):

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimaryDark">@color/your_custom_color</item>
</style>

На уровне API 21+ вы также можете использовать метод Window.setStatusBarColor() из кода.

Из его документов:

Чтобы это вступило в силу, окно должно рисовать фоны системной панели с помощью WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS и WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS не должны быть установлены. Если цвет непрозрачен, рассмотрите возможность установки View.SYSTEM_UI_FLAG_LAYOUT_STABLE и View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN.

earthw0rmjim
06 сен. 2016, в 07:24

Поделиться

Строка состояния — системное окно, принадлежащее операционной системе.
  На устройствах до 5.0 для Android приложения не имеют права изменять свой цвет, поэтому это не то, что библиотека AppCompat может поддерживать более старые версии платформы. Лучшим AppCompat может служить поддержка окраски ActionBar и других общих виджетах пользовательского интерфейса в приложении.

На устройствах после 5.0 для Android
Изменение цвета строки состояния также требует установки двух дополнительных флагов в окне; вам нужно добавить флаг FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS и очистить флаг FLAG_TRANSLUCENT_STATUS.

Window window = activity.getWindow();

// clear FLAG_TRANSLUCENT_STATUS flag:
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

// finally change the color
window.setStatusBarColor(activity.getResources().getColor(R.color.my_statusbar_color));

salik latif
06 сен. 2016, в 08:02

Поделиться

Вы также можете добавить эти строки кода в основное действие

 if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.dark_nav)); // Navigation bar the soft bottom of some phones like nexus and some Samsung note series  
        getWindow().setStatusBarColor(ContextCompat.getColor(this,R.color.statusbar)); //status bar or the time bar at the top
      }

Faakhir
16 нояб. 2017, в 06:46

Поделиться

изменение цвета строки состояния доступно только для Android выше леденец

1. Вы можете изменить цвет строки состояния программно этой строкой:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    getWindow().setStatusBarColor(ContextCompat.getColor(context, R.color.your_color));
}

2. Вы можете сделать это с плавной анимацией перехода:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    int startColor = getWindow().getStatusBarColor();
    int endColor = ContextCompat.getColor(context, R.color.your_color);
    ObjectAnimator.ofArgb(getWindow(), "statusBarColor", startColor, endColor).start();
}

3. или вы можете добавить это к вашему стилю темы в файле values /styles.xml. Элемент colorPrimaryDark будет использоваться для цвета строки состояния вашего приложения

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

shahab yousefi
10 окт. 2018, в 23:05

Поделиться

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

будет отображаться только в Lollipop и больше, чем Lollipop (API).
Постскриптум вам необходимо иметь Theme.AppCompat в качестве основной/основной темы

Aman Grover
06 сен. 2016, в 06:51

Поделиться

добавить цвет строки состояния к вашему стилю и готово

<item name="android:statusBarColor">@color/black</item>

Masoud Darzi
27 янв. 2019, в 10:39

Поделиться

Примечание. — Цвет строки состояния поддерживается на уровне api 19 или 21 и выше уровня api.
Проверьте эту ссылку: изменить цвет строки состояния

Krunal Patel
06 сен. 2016, в 06:26

Поделиться

Ещё вопросы

  • 0Uncaught TypeError: Object [object Object] не имеет метода ‘fnStandingRedraw’
  • 0base64_decode не работает для PHP
  • 0Лак 4, кеш страницы с печеньем
  • 0angularJS проверять ng-repeat поочередно с помощью ng-if
  • 0Загрузка невыровненных двойников в регистр _m128d
  • 1Подключение пиров в Лидгрен с сервера
  • 1python2.7 pip install EnvironmentError Illega последовательность байтов
  • 1разделять запятые значения и хранить в отдельной строке в Python 3.x?
  • 0Уровни изоляции MySQL в nodejs. Каждый запрос в соединении изолирован или каждый пул изолирован?
  • 1Python регулярное выражение вырезать строку шаблона
  • 0Написать регулярное выражение в preg_replace
  • 1Как установить ширину столбцов группы кендогрид
  • 0Как изменить положение значка в ионной вкладке, которая только для заголовка?
  • 0Вызов функции с одного контроллера на другой контроллер с использованием Factory в Angularjs
  • 1Android ThreadSafeClientConnManager Тайм-ауты?
  • 1Не удается сохранить дату календаря в базе данных в Java
  • 1Почему nullpointerexception при разборе xml в приложении для Android?
  • 1Python pandas: добавление информации из словаря в строки во время циклического перебора данных
  • 0Событие мыши два раза срабатывает в Firefox при наведении на элемент. Привести к мерцанию. Есть ли способ изменить это мерцание?
  • 0Используйте мою переменную php в качестве формулы для вычисления чего-либо
  • 0Как получить чистые URL в PHP
  • 1ES6 super () в методах конструктора и прототипа
  • 0Не можете добавить внешний ключ здесь?
  • 0Javascript; Отслеживание onClick для стороннего приложения, которое позволяет только базовое редактирование HTML-кода
  • 0увеличить mpl lower_bound во время выполнения
  • 1Получение представления даты в секундах в Java
  • 1как получить файл в Java (сервлет / JSP)
  • 1API VLC Media Player
  • 1Импортировать проблемную таблицу «hibernate_sequence» с Generation.type
  • 1Можете ли вы написать функцию Firebase, которая запускается только GoogleBot
  • 1Прямой доступ к базе данных Android Media из кода
  • 1Удалить / сохранить пустые строки массива на основе значения идентификатора
  • 1Как выполнить файл конфигурации flume с помощью Java-программы?
  • 1Создание одного процесса в C # для получения нескольких собственных сообщений Chrome
  • 0C ++ сторонняя библиотека включает в себя несуществующий заголовочный файл?
  • 0Изменение заголовка страницы по маршруту из нескольких файлов config.js в угловых
  • 1Растянуть списки, чтобы соответствовать размерам друг друга
  • 0Foreach возвращает один элемент многим
  • 0Исключения в C ++ — что не работает так, как должно
  • 0Попытка заставить функцию интервала работать с моей фабрикой
  • 0Невозможно, чтобы моя панель навигации соответствовала основному телу
  • 0Как проверить, существует ли пользователь в базе данных SQL
  • 1Как получить доступ к PrintSettings из C # с помощью GeckoFX
  • 1Как читать и записывать данные в P6DB через веб-сервис P6 с использованием C #
  • 0Чтение из файла char на char в c ++
  • 0Найти значение ключа в объекте JSON, используя строку в JQuery
  • 1Android: как использовать данные, переданные из родительской активности, в дочернюю активность?
  • 0Digital Ocean подключить одну каплю к базе данных MySQL другой капли
  • 0PHP не возвращает массив
  • 1Результатом math.log в Python pandas является DataFrame.

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

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

  • Как изменить цвет span
  • Как изменить цвет smok rpm 40
  • Как изменить цвет smartart
  • Как изменить цвет serum
  • Как изменить цвет seekbar android studio

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

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