简体   繁体   English

使用GridLayoutManager保存和恢复recyclerview的状态

[英]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位置设置为该保存的实例状态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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