Search code examples
androidandroid-jetpack-composeandroid-statusbar

How to change status Bar Color in Jetpack Compose + Material 3


I'm following the theming tutorial from developer.google. I'm trying to migrate the app to Mat. 3 and modify the status bar's color to match with the background color.

  • After adding android:statusBarColor and android:windowLightStatusBar, nothing changes.

  • I noticed that at the very first moments the app loading, status bar is really as my expected, but a moment later it becomes wrong.

Before: https://i.sstatic.net/i43cL.png

After: https://i.sstatic.net/kMwaP.png

What I've tried:

// res/values/themes.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="Theme.Superheroes" parent="android:Theme.Material.Light.NoActionBar">
        <item name="android:statusBarColor">@color/background_light</item>
        <item name="android:windowLightStatusBar">true</item>
        <item name="android:windowBackground">@color/background_light</item>
    </style>
</resources>
// res/values-night/themes.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="Theme.Superheroes" parent="android:Theme.Material.NoActionBar">
        <item name="android:statusBarColor">@color/background_dark</item>
        <item name="android:windowLightStatusBar">false</item>
        <item name="android:windowBackground">@color/background_dark</item>
    </style>
</resources>

Solution

  • Another way to change it without adding a dependency is at ui.theme/Theme.kt as @2801938 has mentioned:

    @Composable
    fun YourAppTheme(darkTheme...) {
        ...
        val view = LocalView.current
        if (!view.isInEditMode) {
            SideEffect {
                val window = (view.context as Activity).window
                window.statusBarColor = colorScheme.primary.toArgb()
                WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
            }
        }
        ...
    }