Store and restore RecyclerView position not working

安稳与你 提交于 2019-12-11 06:08:32

问题


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.



来源:https://stackoverflow.com/questions/43113234/store-and-restore-recyclerview-position-not-working

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