Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save scroll state in nested RecyclerView

I have a problem in my application. I have main list (recycler view). This list keeps 20 horizontal recycler views. It looks really similar like Netflix app. I need to keep state of every "carousel" in main list. If I move first item to right, next to left, scroll down (first and second items are recycled), rotate the screen, scroll up, I need to have restored position of first and second element.

I know that I should use linearLayout.saveOnInstanceState and onRestoreState but my problem is that every carousel is in main list.

configChanges in AndroidManifest.xml can not come into play...

Thank you!

like image 884
Master Disaster Avatar asked Apr 18 '17 18:04

Master Disaster


1 Answers

As @Ixx mentioned scrollX is always 0. You have to use layoutManager to save and restore scroll position

 val scrollStates = mutableMapOf<Int, Parcelable?>()
override fun onViewRecycled(holder: VH) {
    super.onViewRecycled(holder)

    val key = holder.layoutPosition
    scrollStates[key] = holder.childRecycler.layoutManager.onSaveInstanceState()
}

override fun onBindViewHolder(holder: VH, position: Int) {
    val key = holder.layoutPosition
    val state = scrollStates[key]
    if(state != null){
        holder.childRecycler.layoutManager.onRestoreInstanceState(state)
    }else{

        holder.childRecycler.layoutManager.scrollToPosition(0)
    }
}
like image 192
Evgeniy Avatar answered Sep 28 '22 22:09

Evgeniy