Save scroll state in nested RecyclerView

笑着哭i 提交于 2019-12-06 04:16:14

问题


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!


回答1:


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().



来源:https://stackoverflow.com/questions/43480084/save-scroll-state-in-nested-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!