Junior — Middle
How can you create a collapsing toolbar effect in Jetpack Compose?
sobes.tech AI
Answer from AI
In Jetpack Compose, a collapsing toolbar effect can be created in several ways:
-
Use
LazyColumnorLazyListStateto track scrolling and change the height or transparency of the top component based on the scroll position. -
Apply the Accompanist library, which provides
CollapsingToolbarand other components for implementing such an effect. -
Combine
Modifier.offsetandModifier.graphicsLayerwith the scroll state to animate the collapsing of the toolbar.
Here's a simplified example using LazyColumn and changing height:
val scrollState = rememberLazyListState()
val toolbarHeight = 200.dp
val minToolbarHeight = 56.dp
val offset = minOf(scrollState.firstVisibleItemScrollOffset.toFloat(), with(LocalDensity.current) { (toolbarHeight - minToolbarHeight).toPx() })
val currentHeight = toolbarHeight - with(LocalDensity.current) { offset.toDp() }
Column {
Box(
Modifier
.height(currentHeight)
.fillMaxWidth()
.background(Color.Blue)
) {
Text("Toolbar", Modifier.align(Alignment.Center), color = Color.White)
}
LazyColumn(state = scrollState) {
items(100) { index ->
Text("Item #$index", Modifier.padding(16.dp))
}
}
}
This code changes the height of the panel depending on the list scroll, creating a collapsing effect.