2

我在片段中使用 GridLayoutManager 作为 RecyclerView 的 LayoutManager,并且 RecyclerView 适配器由加载器填充。我尝试在设备旋转时存储和恢复 GridLayoutManager 的状态,但无法正常工作,并且仍然回到初始状态“RecyclerView 中的第一个元素”。

onSaveInstanceState 方法:

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

onViewStateRestored 方法:

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

onLoadFinished 方法:

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

1 回答 1

2

尝试包装onRestoreInstanceState()在 Handler 中:

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

延迟onRestoreInstanceState. 我遇到过同样的问题,IMO 看起来 RecyclerView 一直回到初始状态,因为当我们调用onRestoreInstanceState.

于 2017-07-30T10:34:34.183 回答