我看到了很多关于这个主题的相关问题,但没有一个对我有帮助。我正在使用一个交错网格布局对于我的 RecyclerView (显示cards)。
每个 CardView 都会打开一个新活动,我面临的问题是,在从该新活动返回时,RecyclerView 会滚动回顶部。我希望它保留之前滚动的位置。
这是我现在用来设置布局的:
rv.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
rv.setHasFixedSize(true);
对于新手来说有什么合适的工作解决方案吗?
EDIT :
@Override
protected void onResume() {
super.onResume();
if (listState != null) {
rvlayout.onRestoreInstanceState(listState);
}
initializeData();
}
Layout :
RecyclerView.LayoutManager rvlayout = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
并初始化数据:
public void initializeData() {
rv.setLayoutManager(rvlayout);
rv.setHasFixedSize(true);
persons.clear();
c = db.rawQuery(SELECT_SQL, null);
c.moveToFirst();
if (!c.moveToFirst())
return;
while (!c.isLast()) {
id = c.getString(0);
names = c.getString(1);
age = c.getString(2);
persons.add(new Person(id,names,age));
c.moveToNext();
}
adapter = new RVAdapter(persons);
rv.setAdapter(adapter);
}
正确的方法是保存 RecyclerView 滚动位置的状态,并在 Activity 之间切换时恢复它。
1. 要保存它,请重写 onSaveInstanceState()
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putParcelable(LIST_STATE_KEY, layoutManager.onSaveInstanceState());
}
2. 检索数据覆盖 onRestoreInstanceState()
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
Parcelable listState = state.getParcelable(LIST_STATE_KEY);
}
3.最后在onResume()方法中更新LayoutManager
@Override
protected void onResume() {
super.onResume();
if (listState != null) {
layoutManager.onRestoreInstanceState(listState);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)