[英]Android: RecyclerView GridLayoutManager - Restoring scroll position doesn't work properly
I have 3 activities: A --> B --> C 我有3个活动:A-> B-> C
In Activity B, I'm populating using RecyclerView's GridlayoutManager. 在活动B中,我正在使用RecyclerView的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.
我想导航到活动C时保存滚动状态,并从活动C返回活动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);
}
}
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. 但这在我从活动B按返回按钮并转到活动A,然后从活动A导航回活动B时起作用。
Restore state in the onRestoreInstanceState() 在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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.