Building Contextual Mode of Top App Bar in Jetpack Compose | by Tushar Kathuria | Feb, 2022

Creating custom Android UIs just got a whole lot simpler

Tushar Kathuria
Photo by Ales Nesetril on Unsplash

Well, if you are interested in directly jumping to code, here is the link to the activity file that contains the code for achieving the above result.

This post assumes that you already know about Jetpack Compose and the Material Top App Bar implementation. Refer to the following links for a recap:

We will start by creating a Scaffold with a top app bar and a button that toggles the contextual mode. On button click, app bar colors are toggled and share action is added to indicate the contextual mode.

Let us also change the status bar color when contextual mode is toggled. For this we will use Accompanist’s System UI Controller:

implementation "com.google.accompanist:accompanist-systemuicontroller:$accompanist_version"

Let us use updateTransition API to animate the color changes. Replace the color variables with the following initialisation:

We will use the combination of setDecorFitsSystemWindows API and the Accompanist’s Insets to get control of the space behind status bar.

implementation "com.google.accompanist:accompanist-insets:$accompanist_version"
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
ProvideWindowInsets {
.
.
.
}
}
SideEffect {
systemUiController.setStatusBarColor(
color = Color.Transparent,
darkIcons = !isContextual
)
}
TopAppBar(
.
.
.
modifier = Modifier.background(statusBarColor).statusBarsPadding()
)

Let us use the workaround suggested by Philip Dukhov to solve this issue.

TopAppBar(
.
.
.
modifier = Modifier.background(statusBarColor).statusBarsPadding().bottomElevation()
)
  • Build a custom top app bar component that takes isContextual boolean parameter. This will enable us to use it across all screens of the app
  • Support dark theme by using semantic colors from theme instead of hardcoded colors

Leave a Comment