Sergio76
Sergio76

Reputation: 3996

Colors of the status bar using the DayNight theme in android

I am applying the theme Theme.AppCompat.DayNight.NoActionBar to my application.

In the light theme, I want the status bar to be white and in the dark theme, I want it to be dark.

I can't get the status bar to be white and the letters to be dark and vice versa.

This is my style:

 <style name="AppTheme.Base" parent="Theme.AppCompat.DayNight.NoActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorControlNormal">@color/primary_dark</item>
        <item name="colorControlHighlight">@color/primary_dark</item>
        <item name="android:textColorPrimary">@color/letter_medium_emphasis</item>
        <item name="android:textColorSecondary">@color/letter_high_emphasis</item>
    </style>

and this is my color file:

<resources>
    <color name="primary">#ffffff</color>
    <color name="primary_dark">#0336ff</color>
    <color name="letter_high_emphasis">#de000000</color>
    <color name="letter_medium_emphasis">#99000000</color>
    <color name="letter_medium_disabled">#61000000</color>
</resources>

I have tried adding the parameter <item name="android:statusBarColor">@color/primary</item>
But I still get the same thing, the status bar is white and the status bar text is also white.

What is the way to show the white status bar with dark letters in the light theme and vice versa in the dark theme?

Upvotes: 10

Views: 6138

Answers (1)

CzarMatt
CzarMatt

Reputation: 1833

You can use isLightTheme attr:

https://developer.android.com/reference/android/R.attr#isLightTheme

Add it to your themes.xml like so:

<item name="android:windowLightStatusBar">?attr/isLightTheme</item>

The value returned by ?attr/isLightTheme is handled by the system. You can also get the currently set value via:

AppCompatDelegate.getDefaultNightMode();

OR

Configuration config = getResources().getConfiguration();
int nightMode = configuration.uiMode & Configuration.UI_MODE_NIGHT_MASK;

Together with android:statusBarColor you can control your status bar in both light and dark theme automatically.

Also, I had much better luck using parent="Theme.MaterialComponents.DayNight" for my base theme when using this attr value.

Upvotes: 33

Related Questions