I am trying to add a scrollable behavior to the topBar parameter of Scaffold. In the documentation it says, that I can add the scrollable behavior by setting the CenterAlignedTopAppBar parameter scrollBehavior
. However it doesn't seem to work.
The following answer from StackOverflow didn't help.
Any advice appreciated.
Here is how my code goes.
@Composable
fun Screen() {
val topAppBarScrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior(
rememberTopAppBarState(),
{ true },
spring(Spring.StiffnessMediumLow),
rememberSplineBasedDecay()
)
val scrollBehavior = remember { topAppBarScrollBehavior }
Scaffold(
topBar = {
ThemedTopBar(scrollBehavior, title = "Select Guests", onBack = {/* TODO */})
}
) { innerPadding ->
//MainContent(innerPadding)
}
}
@Composable
fun ThemedTopBar(scrollBehavior: TopAppBarScrollBehavior, title: String, onBack: () -> Unit) {
CenterAlignedTopAppBar(
modifier = Modifier
.height(51.dp)
.padding(vertical = 16.dp, horizontal = 9.dp)
,
title = {
Text(
text = title,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = Typography.titleMedium
)
},
navigationIcon = {
IconButton(
modifier = Modifier.size(22.dp),
onClick = onBack,
) {
Icon(
painter = painterResource(id = R.drawable.ic_baseline_arrow_back),
contentDescription = "Back Button",
tint = ThemeBlue
)
}
},
scrollBehavior = scrollBehavior
)
}
You have to attach the TopAppBarScrollBehavior.nestedScrollConnection
to a Modifier.nestedScroll
in order to keep track of the scroll events.
Something like:
val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
CenterAlignedTopAppBar(
title = { /* .. */ },
navigationIcon = { /* .. */ },
actions = { /* .. */ },
scrollBehavior = scrollBehavior
)
},
content = { /* .. */ }
)