Sobes.tech
Junior — Middle

How can you ensure the scroll position in RecyclerView is preserved when recreating an Activity?

sobes.tech AI

Answer from AI

To preserve the scroll position in RecyclerView when recreating an Activity, you can save and restore the state of the LayoutManager.

Example for LinearLayoutManager:

// Saving position
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
val scrollPosition = layoutManager.findFirstVisibleItemPosition()

// Save to Bundle, for example in onSaveInstanceState
outState.putInt("scroll_position", scrollPosition)

// Restoring position in onCreate or onRestoreInstanceState
val position = savedInstanceState?.getInt("scroll_position") ?: 0
recyclerView.scrollToPosition(position)

If more precise restoration is needed (for example, considering the offset within the item), you can save the Parcelable state of the LayoutManager:

// Saving
val layoutState = recyclerView.layoutManager?.onSaveInstanceState()
outState.putParcelable("layout_state", layoutState)

// Restoring
val layoutState = savedInstanceState?.getParcelable<Parcelable>("layout_state")
recyclerView.layoutManager?.onRestoreInstanceState(layoutState)

Thus, when recreating the Activity, the scroll position will be saved and restored correctly.