如何在其他活动的后按中保留“回收者"视图的滚动位置? [英] How to retain the scrolled position of a Recycler view on back press from another activity?
问题描述
我看到了许多与此主题相关的问题,但是没有一个问题对我有帮助.我的RecyclerView使用的是 StaggeredGridLayout (显示卡片). 每个CardView都会打开一个新活动,我面临的问题是,在该新活动上按一下后,RecyclerView会滚动回到顶部.我希望它保留以前的滚动位置.
I saw many related questions about this topic, but none of them helped me. I am using a StaggeredGridLayout for my RecyclerView (showing cards). Every CardView opens a new activity, the problem I am facing is that on back press from that new activity, the RecyclerView scrolls back to the top. I want it to retain the previously scrolled position.
这是我现在用来设置布局的内容:
rv.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
rv.setHasFixedSize(true);
任何适合新手的可行解决方案?
Any proper working solution for a newbie?
@Override
protected void onResume() {
super.onResume();
if (listState != null) {
rvlayout.onRestoreInstanceState(listState);
}
initializeData();
}
布局:
RecyclerView.LayoutManager rvlayout = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
和initializeData:
and initializeData :
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滚动位置的状态并在活动"之间进行切换时将其还原.
The proper way to do it is to save the state of RecyclerView scroll position and restore it while switching between Activities.
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);
}
}
这篇关于如何在其他活动的后按中保留“回收者"视图的滚动位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!