0

The LazyRow LazyListState has the method animateScrollToItem which scrolls to the end of a list item

I want to scroll to the center of the listItem.

I can do that by passing a scrollOffset to the animateScrollToItem, something like listItem.width / 2 , but I was not able to figure out the width of the listItem I want to scroll.

The LazyListState provides the val visibleItemsInfo: List<LazyListItemInfo> list and I can do something like this

suspend fun LazyListState.animateScrollEndCenter(index: Int) {
    val itemInfo = this.layoutInfo.visibleItemsInfo.firstOrNull { it.index == index }
    if (itemInfo != null) {
        val center = this@animateScrollEndCenter.layoutInfo.viewportEndOffset / 2
        val itemCenter = itemInfo.offset + itemInfo.size / 2
        this@animateScrollEndCenter.animateScrollBy((itemCenter - center).toFloat())
    } else {
        this@animateScrollEndCenter.animateScrollToItem(index)
    }
}

but visibleItemsInfo is nullable, so it does not have information about the listItem.width, until the listItem is presented on the screen

In the following example, I'm scrolling to the listItem 11

When is on the screen

https://i.stack.imgur.com/k0fk2.gif

When is out of the screen

https://i.stack.imgur.com/P554i.gif

I want to scroll to the center of the LazyRow listItem

Filipe h
  • 3
  • 2
  • The behavior you need is already presented in `Accompaniet Pager`. Try to check it source code (or mayby use it instead?). https://google.github.io/accompanist/pager/ – Dwane13 Jan 25 '23 at 09:56
  • hi @Dwane13 , this could work, but this is part of a huge App Main screen, it will be very risky to add something in alpha testing – Filipe h Jan 25 '23 at 15:44
  • Don't worry. Despite being in alpha accompaniest libs are stable and use latest compose version. They are also developed by Google, as far as i remember – Dwane13 Jan 26 '23 at 18:50

0 Answers0