iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article

Restoring Scroll Position in LazyRow with Fragment(RecyclerView)

に公開

I was disappointed when the scroll position of a LazyRow was lost during screen transitions or scrolling, so I've documented how I addressed it.

ViewModel

Prepare index and offset fields in the ViewModel.

var offset = 0
    private set
var index = 0
    private set
    
fun setScrollPosition(index: Int, offset: Int) {
    offset = offset
    index = index
}

Composable

In the Composable, you just need to notify the ViewModel of the index and offset and set the scroll state.

@Composable
fun Sample(
    viewModel: ViewModel
) {
    val scrollPosition = LazyListState(viewModel.index, viewModel.offset)
    
    DisposableEffect(viewModel) {
        onDispose {
            viewModel.setScrollPosition(scrollPosition.firstVisibleItemIndex, scrollPosition.firstVisibleItemScrollOffset)
        }
    }
    
    LazyRow(
        state = scrollPosition
    ) {
        ...
    }
}
  • Notify the ViewModel of the scroll position when leaving via DisposableEffect
  • Create LazyListState using the index and offset held by the ViewModel
  • Set the LazyListState to the LazyRow

That's all.
*Note: Since I wrote this code directly in the article, it might not work if you copy and paste it, or there might be some issues.

Discussion