以下是我的代码中的内容,但这并不是保存和恢复滚动位置的状态。我试图保存滚动位置并在用户旋转手机时恢复它。
@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);
}
}
答案 0 :(得分:0)
在使用recyclerview的活动中添加onOrientationChanged并将recyclerview位置设置为该已保存的实例状态