How to save scroll position of RecyclerView in Android?

后端 未结 8 1400
耶瑟儿~
耶瑟儿~ 2020-11-27 06:20

I have Recycler view which lays inside of SwipeRefreshLayout. Also, have ability to open each item in another activity. After returning back to Recycler I need scroll to cho

8条回答
  •  没有蜡笔的小新
    2020-11-27 06:43

    A lot of these answers seem to be over complicating it.

    The LayoutManager supports onRestoreInstanceState out of the box so there is no need to save scroll positions etc. The built in method already saves pixel perfect positions.

    example fragment code (null checking etc removed for clarity):

    private Parcelable listState;
    private RecyclerView list;
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        listState=savedInstanceState.getParcelable("ListState");
    
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    
        outState.putParcelable("ListState", list.getLayoutManager().onSaveInstanceState());
    
    }
    

    then just call

    list.getLayoutManager().onRestoreInstanceState(listState);
    

    once your data has been reattached to your RecyclerView

提交回复
热议问题