Store and restore RecyclerView position not workin

2019-07-27 00:54发布

问题:

I am using GridLayoutManager as LayoutManager for RecyclerView inside a fragment , and RecyclerView adapter get populated by loader. I tried to store and restore state of GridLayoutManager on device rotation but not working and still get back to the initial state "first element in RecyclerView".

onSaveInstanceState method:

    @Override
public void onSaveInstanceState(Bundle outState) {
    mRecylcerViewParecelable = mGridView.getLayoutManager().onSaveInstanceState();
    outState.putParcelable(GRID_LAYOUT_PARCEL_KEY, mRecylcerViewParecelable);
    super.onSaveInstanceState(outState);
}

onViewStateRestored method:

    @Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
    if(savedInstanceState!=null){
        mRecylcerViewParecelable = savedInstanceState.getParcelable(GRID_LAYOUT_PARCEL_KEY);
    }
    super.onViewStateRestored(savedInstanceState);
}

onLoadFinished method:

    @Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    mMovieAdapter.swapCursor(data);
  mGridView.getLayoutManager().onRestoreInstanceState(mRecylcerViewParecelable);}

回答1:

Try to wrap onRestoreInstanceState() inside Handler:

new Handler().postDelayed(new Runnable() {
            @Override public void run() {
                mGridView.getLayoutManager().onRestoreInstanceState(listState);
            }
        }, 300);

It's a hack to delay the onRestoreInstanceState. I've experienced the same issue, IMO it looks like the RecyclerView keeps going back to initial state because the data in Adapter still being populated when we call the onRestoreInstanceState.