Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 664
iknow Avatar asked Nov 29 '20 21:11

iknow


People also ask

How do I display a collection of items in jetpack compose?

Many apps need to display collections of items. This document explains how you can efficiently do this in Jetpack Compose. If you know that your use case does not require any scrolling, you may wish to use a simple Column or Row (depending on the direction), and emit each item’s content by iterating over a list like so:

How does the lazycolumn list work?

As currently implemented, the LazyColumn list is populated directly from an array of string values. The goal is now to group those items by manufacturer, with each group preceded in the list by a sticky header displaying the manufacturer’s name.

What is the difference between lazycolumn and lazyrow in compose?

LazyColumn produces a vertically scrolling list, and LazyRow produces a horizontally scrolling list. The lazy components are different to most layouts in Compose.

How to set current tab of text in lazycolumn?

LazyColumn ( ... modifier = Modifier.nestedScroll (nestedScrollConnection) ) { items (...) { Text ("Your text...") } } You can use the LazyListState.firstVisibleItemIndex property (obtained via rememberLazyListState and set as the state parameter to LazyColumn) and set the current tab based on that.


Video Answer


1 Answers

With 1.0.x LazyListState supports the scroll position via

  • the scrollToItem() function, which ‘immediately’ snaps the scroll position,
  • animateScrollToItem() which scrolls using an animation

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")
}

  
like image 123
Gabriele Mariotti Avatar answered Sep 19 '22 03:09

Gabriele Mariotti