LayoutManager.onSaveInstanceState() not working

∥☆過路亽.° 提交于 2019-12-23 04:55:09

问题


I'm trying to save state of my RecyclerView with GridLayoutManager, but when calling onSaveInstanceState() of activity and when I try to call onSaveInstanceState() on layout manager that always return the same object. I trying use method "findFirstVisibleItemPosition", but it always return -1.

RecyclerView has adapter, adapter has some amount of elements, I can scroll them! I don't know why I can't get item position of fully initialized and working component! Please help!

There is my code:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putParcelable(BUNDLE_MOVIES_RECYCLER_VIEW_STATE, mMoviesRecyclerView.getLayoutManager().onSaveInstanceState());

    outState.putInt(BUNDLE_SEGMENT_POSITION, mSelectedFilterPosition);
    outState.putSerializable(BUNDLE_NOW_PLAYING_MOVIE, mNowPlayingMovie);
    outState.putSerializable(BUNDLE_SEGMENTED_MOVIES, mSegmentMovies);
}

回答1:


Problem was resolved! For saving state of layout manager need call method LayoutManager.onSaveInstanceState() in onPause method of activity. Because in onSaveInstanceState of activity LayoutManager already clear it child from view or just drop layout configuration. Sample of code:

public class MainActivity extends AppCompatActivity {

 RecyclerView recyclerView;
 private Parcelable mLayoutManagerState;
 private static final String LAYOUT_MANAGER_STATE = "LAYOUT_MANAGER_STATE";

 @Override
 protected void onPause() {
    super.onPause();

    mLayoutManagerState = recyclerView.getLayoutManager().onSaveInstanceState();
 }

 @Override
 public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
    super.onCreate(savedInstanceState, persistentState);
    recyclerView = (RecyclerView) findViewById(R.id.recyclerview);

    if (savedInstanceState != null) {
        mLayoutManagerState = savedInstanceState.getParcelable(LAYOUT_MANAGER_STATE);
        recyclerView.getLayoutManager().onRestoreInstanceState(mLayoutManagerState);
    }
 } 

 @Override
 public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    super.onSaveInstanceState(outState, outPersistentState);

    outState.putParcelable(LAYOUT_MANAGER_STATE, mLayoutManagerState);
 }
}


来源:https://stackoverflow.com/questions/47110168/layoutmanager-onsaveinstancestate-not-working

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