我正在使用 gridlayoutManager 填充 recyclerView。现在我想保存屏幕旋转的滚动位置。
我尝试使用 onSaveInstanceState 和 onRestoreInstanceState() 来执行此操作,如本文所示:
如何使用RecyclerView.State保存RecyclerView滚动位置? https://stackoverflow.com/questions/27816217/how-to-save-recyclerviews-scroll-position-using-recyclerview-state
下面是我的代码:
@Override
protected void onSaveInstanceState(Bundle outState) {
Log.e(TAG, "onSaveInstanceState");
super.onSaveInstanceState(outState);
outState.putParcelable(KEY_INSTANCE_STATE_RV_POSITION,
gridLayoutManager.onSaveInstanceState());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.e(TAG, "onRestoreInstanceState");
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState!= null){
Parcelable savedState =
savedInstanceState.getParcelable(KEY_INSTANCE_STATE_RV_POSITION);
movieAdapter.addAll(movieItemList);
if (savedState!= null){
gridLayoutManager.onRestoreInstanceState(savedState);
}
}
}
//this is my movieAdapter.addAll() method
public void addAll(List<MovieItem>items){
movieItems = items;
}
//This is the method to get lists of movies from ViewModel Class
private void loadFavMovies() {
FavViewModel favViewModel =
ViewModelProviders.of(MainActivity.this).get(FavViewModel.class);
favViewModel.getFavListLiveData().observe(MainActivity.this, new
Observer<List<FavlistItem>>() {
@Override
public void onChanged(List<FavlistItem> favlistItems) {
if (!favlistItems.isEmpty()) {
loadingIndicator.setVisibility(View.GONE);
movieRecycler.setVisibility(View.GONE);
favRecycler.setVisibility(View.VISIBLE);
favAdapter.setFavlistItems(favlistItems);
Toast.makeText(getApplicationContext(), "Swipe Left Or
Right To remove Item",Toast.LENGTH_SHORT).show();
}else {
loadingIndicator.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "No Favorite
Movies",Toast.LENGTH_SHORT).show();
}
}
});
}
这是该项目的 GitHub 链接https://github.com/harshabhadra/Movies-Mela https://github.com/harshabhadra/Movies-Mela
我知道我迟到了,但如果有帮助的话仍然!!
存储回收器视图位置比其他答案使它看起来简单得多
您可以这样做
首先创建一个成员变量
Parcelable state;
Now,
@Override
protected void onPause() {
super.onPause();
state = recyclerView.getLayoutManager().onSaveInstanceState();
}
@Override
protected void onResume() {
super.onResume();
recyclerView.getLayoutManager().onRestoreInstanceState(state);
}
使用上面的代码覆盖 onpause 和 onresume 方法,你就可以开始了!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)