当 ListView
位于 ListFragment
中时,如何保存 ListView
的滚动位置?
最佳答案
最后我解决了这个问题,所以我决定将解决方案发布给其他人:
在我的 ListFragment 子类中,我声明了两个 int 变量来保存滚动位置
public static class MyListFragment extends ListFragment {
......................
......................
private int index = -1;
private int top = 0;
......................
然后覆盖 onPause() 和 onResume() 以保存和恢复 ListView
的滚动位置,如下所示:
@Override
public void onResume() {
super.onResume();
......................
......................
setListAdapter(mAdapter);
if(index!=-1){
this.getListView().setSelectionFromTop(index, top);
}
......................
......................
}
@Override
public void onPause() {
super.onPause();
try{
index = this.getListView().getFirstVisiblePosition();
View v = this.getListView().getChildAt(0);
top = (v == null) ? 0 : v.getTop();
}
catch(Throwable t){
t.printStackTrace();
}
......................
......................
}
就是这样!!我希望这会对某些人有所帮助。 :)
关于android - fragment 中的 ListView 无法保存滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9803569/