简体   繁体   中英

Android: RecyclerView GridLayoutManager - Restoring scroll position doesn't work properly

I have 3 activities: A --> B --> C

In Activity B, I'm populating using RecyclerView's GridlayoutManager. I want to save the scrolled state when i navigate to Activity C and restore the scrolled state when i go back to Activity B from Activity C.

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);
    }
}

But this works when I press back button from Activity B and go to Activity A, and navigating back to Activity B from Activity A.

Restore state in the 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM