Sobes.tech
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:

  1. Use LazyColumn or LazyListState to track scrolling and change the height or transparency of the top component based on the scroll position.

  2. Apply the Accompanist library, which provides CollapsingToolbar and other components for implementing such an effect.

  3. Combine Modifier.offset and Modifier.graphicsLayer with 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.