Search code examples
androidandroid-layoutandroid-recyclerviewandroid-viewandroid-scrollview

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!


Solution

  • You can save scrollX position when you item of RecyclerView is being recycled, and then scroll that much when that item is being bind again:

    int[] scrollXState = new int[20]; // assuming there are 20 carousel items
    
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        // setup recycler here, then post scrollX after recycler has been laid out
        holder.nestedRecyclerView.post(() ->
                holder.nestedRecyclerView.setScrollX(scrollXState[holder.getAdapterPosition()]));
    }
    
    @Override
    public void onViewRecycled(MyViewHolder holder) {
        scrollXState[holder.getAdapterPosition()] = holder.nestedRecyclerView.getScrollX();
        super.onViewRecycled(holder);
    }
    
    class MyViewHolder extends RecyclerView.ViewHolder {
    
        RecyclerView nestedRecyclerView;
    
        public MyViewHolder(View itemView) {
            super(itemView);
        }
    }
    

    Only thing you should take care of is that you do not want parent adapter to be destroyed and created after orientation change, make it survive orientation change. Otherwise save int[] into Bundle and then get it back from onRestoreInstanceState().