3

我有 3 个活动:A --> B --> C

在活动 B 中,我使用 RecyclerView 的 GridlayoutManager 进行填充。我想在导航到 Activity C 时保存滚动状态,并在我从 Activity C 返回到 Activity B 时恢复滚动状态。

private RecyclerView mImgList;
private GridLayoutManager mRecyclerGridMan;
private final String KEY_RECYCLER_STATE = "recycler_state";
private Parcelable mListState = null;
private static Bundle mBundleRecyclerViewState;

.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

.

@Override
protected void onPause()
{
    super.onPause();
    mBundleRecyclerViewState = new Bundle();
    mListState = mImgList.getLayoutManager().onSaveInstanceState();
    mBundleRecyclerViewState.putParcelable(KEY_RECYCLER_STATE, mListState);
}

.

@Override
protected void onResume()
{
    super.onResume();
    if (mBundleRecyclerViewState != null) {
        mListState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
        mImgList.getLayoutManager().onRestoreInstanceState(mListState);
    }
}

但是,当我从 Activity B 按下返回按钮并转到 Activity A,然后从 Activity A 导航回 Activity B 时,这会起作用。

4

1 回答 1

0

在 onRestoreInstanceState() 中恢复状态

protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);

// Retrieve list state and list/item positions
if(state != null)
   mListState =   mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
}
于 2016-11-14T08:07:05.373 回答