简体   繁体   中英

Saving and restoring state of recyclerview with GridLayoutManager

The following is what I have in my code, but this isn't saving and restoring the state of my scroll position. I am trying to save the scroll position and restore it when user rotates the phone.

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

    mRecyclerView = (RecyclerView) findViewById(R.id.rv_main_activity);
    mRecyclerView.setHasFixedSize(true);
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        mRecyclerView.setLayoutManager(mGridLayoutManager = new GridLayoutManager(this, 3));
    } else {
        mRecyclerView.setLayoutManager(mGridLayoutManager = new GridLayoutManager(this, 5));
    }

    mMoviesAdapter = new MoviesAdapter(this, this);
    mRecyclerView.setAdapter(mMoviesAdapter);

    if (Build.VERSION.SDK_INT > 10) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    getSupportLoaderManager().initLoader(ID_MOVIE_LOADER, null, this);
    MoviesSyncTask.syncMovies(this, "popular");

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelable(SCROLL_POSITION, mRecyclerView.getLayoutManager().onSaveInstanceState());
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if (savedInstanceState != null) {
        mListState = savedInstanceState.getParcelable(SCROLL_POSITION);
        mRecyclerView.getLayoutManager().onRestoreInstanceState(mListState);
    }
}

在使用recyclerview的活动中,添加onOrientationChanged并将recyclerview位置设置为该保存的实例状态

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