android-jetpack-composescrollableandroid-jetpack-compose-lazy-column

Automatically scroll up the lazy column to display the full height of the card when expanded


This code does not work as expected. I want lazy column to automatically scroll up to display the entire height of the card when expanded.

val listState = rememberLazyListState()
val coroutineScope = rememberCoroutineScope()

LazyColumn(
    state = listState
) {
    itemsIndexed(items) { index, item ->
        ExpandableCard(
            item = item,
            isExpanded = expandedCardsStates[item.id] ?: false,
            onCardClicked = {
                viewModel.expandedState(item.id)
                coroutineScope.launch {
                    listState.animateScrollToItem(index = index)
                }
            }
        )
    }
}

Here's how it appears with this code when I expand the last card:

enter image description here

Here's the expected behaviour:

enter image description here


Solution

  • Using animateScrollToItem is not going to give you satisfactory results. It will attempt to scroll the LazyColumn so that the given item is at the top of the LazyColumn. If the item is the last one on screen, this will result in a stuttering animation. Another problem is that the scrolling might already be performed while the animation is still in progress, resulting in a not fully visible item.

    What you probably want is to only scroll the LazyColumn if the expanded item is not fully visible on the screen. To detect these cases, add a onGoballyPositioned Modifier on the AnimatedVisibility:

    @Composable
    fun ExpandableCard(/** ... **/ ) {
    
        var isFullyVisible by remember {
            mutableStateOf(true)  // stores whether the expanded content is fully visible on screen
        }
        var contentHeightPx by remember {
            mutableStateOf(0f)  // stores the height of the expanded content
        }
    
        Card(
            //...
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                // ...
    
                AnimatedVisibility(
                    modifier = Modifier.onGloballyPositioned { coordinates ->
                        val (width, height) = coordinates.size
                        val (x1, y1) = coordinates.positionInRoot()
                        val x2 = x1 + width
                        val y2 = y1 + height
                        val screenWidth: Float = configuration.screenWidthDp.toPx
                        val screenHeight: Float = configuration.screenHeightDp.toPx
                        isFullyVisible = (x1 >= 0 && y1 >= 0) && (x2 <= screenWidth && y2 <= screenHeight)
                        contentHeightPx = coordinates.size.height.toFloat()
                    },
                    visible = isExpanded,
                    enter = expandVertically() + fadeIn(),
                    exit = shrinkVertically() + fadeOut()
                ) {
                    //...
                }
            }
        }
    }
    

    You need to add the following extension function:

    val Number.toPx
        get() = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            this.toFloat(),
            Resources.getSystem().displayMetrics
        )
    

    Next, we need to make sure that the scrolling is only performed after the animation of AnimatedVisibility was completed. We need to add a seperate callback function to the ExpandableCard Composable. Also, we change the function return type of onCardClicked from Job to Unit:

    @Composable
    fun ExpandableCard(/** ... **/ onCardClicked: () -> Unit, onCardExpanded: (Float) -> Job) {
        //...
    }
    

    Then, we call the onCardExpanded once the expand animation was finished:

    AnimatedVisibility(
        //...
    ) {
    
        val animatedVisibilityScope = this
    
        LaunchedEffect(animatedVisibilityScope.transition.isRunning) {
            if (!animatedVisibilityScope.transition.isRunning &&
                animatedVisibilityScope.transition.currentState == EnterExitState.Visible
            ) {
                if (!isFullyVisible) {
                    // If the content is not fully visible, scroll LazyColumn
                    onCardExpanded(contentHeightPx)
                }
            }
        }
    
        // expanded content
    }
    

    Finally, apply the scroll in the LazyColumn:

    LazyColumn(
        modifier = Modifier
            .fillMaxHeight()
            .padding(start = 20.dp, end = 20.dp, top = 20.dp),
        state = listState
    ) {
        itemsIndexed(items) { index, item ->
            ExpandableCard(
                engagementPointItem = item,
                isExpanded = expandedCardsStates[item.id] ?: false,
                onCardClicked = {
                    viewModel.toggleExpandedState(item.id)
                },
                onCardExpanded = { scrollAmount ->
                    coroutineScope.launch {
                        listState.animateScrollBy(scrollAmount + 50)
                    }
                }
            )
        }
    }
    

    Output:

    enter image description here