androidkotlinandroid-jetpack-composeandroid-jetpack-compose-listandroid-jetpack-compose-lazy-column

Jetpack Compose LazyColumn programmatically scroll to Item


Is there any way to programmatically scroll LazyColumn to some item in the list? I thought that it can be done by hoisting the LazyColumn argument state: LazyListState = rememberLazyListState() but I have no idea how I can change this state e.g. on Button click.


Solution

  • The LazyListState supports the scroll position via

    Something like:

    val listState = rememberLazyListState()
    // Remember a CoroutineScope to be able to launch
    val coroutineScope = rememberCoroutineScope()
    
    LazyColumn(state = listState) {
        // ...
    }
    
    Button (
        onClick = { 
            coroutineScope.launch {
                // Animate scroll to the 10th item
                listState.animateScrollToItem(index = 10)
            }
        }
    ){
        Text("Click")
    }