I have an application, where all of screens except 2-3 screens have the same statusbar color.
So the purpose is to change statusbar color when this screen is opened and reset statusbar color to default color from theme when this screen is closed.
I am trying to implement it with DisposableEffect
:
DisposableEffect(Unit) {
systemUiController.setStatusBarColor(color = anotherColor)
onDispose {
systemUiController.setStatusBarColor(color = defaultColor)
}
}
It works, but with delays, not synchronously with TopAppBar:
What is the way to implement it correctly?
I think the delay is inevitable, I've never seen it change instantly.
I always opt-in for a transparent status bar + draw behind systembars and handle everything on my own. And drawing behind system bars is the new recommended approach. Since you are already using compose, this is very easy with help of accompanist lib + compose 1.2.0 has inset modifiers built in to help with this.
request your activity to be laid out edge-to-edge (draw behind system bars)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
}
Using accompanist UIController lib, set status bar colors to transparent.
systemUiController.setSystemBarsColor(
color = Color.Transparent,
darkIcons = useDarkIcons
)
In your composables, where needed, consume the appropriate insets.
Modifier.fillMaxSize()
.statusBarsPadding() //status bar insets
.navigationBarsPadding() //nav bar insets
.systemBarsPadding() //both
EDIT: you could create a disposable effect wrapper to switch system icons, and use it everywhere you need. For example: (you can improve this)
@Composable
fun initSystemUi(
useDarkIcons: Boolean = MaterialTheme.colors.isLight,
systemUiController: SystemUiController = rememberSystemUiController()
) {
DisposableEffect(Unit) {
systemUiController.setSystemBarsColor(
color = Color.Transparent,
darkIcons = useDarkIcons
)
onDispose {
systemUiController.setSystemBarsColor(
color = Color.Transparent,
darkIcons = useDarkIcons
)
}
}
}