【发布时间】:2011-02-13 01:52:44
【问题描述】:
可能重复:
Maintain/Save/Restore scroll position when returning to a ListView
当我转到另一个活动(通过启动另一个意图)然后返回(按返回按钮)时,如何保持我的 ListView 在活动中的位置?
谢谢。
【问题讨论】:
标签: android
可能重复:
Maintain/Save/Restore scroll position when returning to a ListView
当我转到另一个活动(通过启动另一个意图)然后返回(按返回按钮)时,如何保持我的 ListView 在活动中的位置?
谢谢。
【问题讨论】:
标签: android
@Override
protected void onPause()
{
// Save scroll position
SharedPreferences preferences = context.getSharedPreferences("SCROLL", 0);
SharedPreferences.Editor editor = preferences.edit();
int scroll = mListView.getScrollY();
editor.put("ScrollValue", scroll);
editor.commit();
}
@Override
protected void onResume()
{
// Get the scroll position
SharedPreferences preferences = context.getSharedPreferences("SCROLL", 0);
int scroll = preferences.getInt("ScrollView", 0);
mListView.scrollTo(0, scroll);
}
【讨论】:
您应该使用onSaveInstanceState 来存储滚动位置,然后使用onCreate 或onRestoreInstanceState 来恢复它。
【讨论】:
声明全局变量:
int index = 0;
ListView list;
并在onCreate() 中引用您的ListView:
list = (ListView) findViewById(R.id.my_list);
接下来,在onResume()的末尾添加这一行:
list.setSelectionFromTop(index, 0);
最后,在onPause 的末尾添加以下行:
index = list.getFirstVisiblePosition();
【讨论】:
请注意,使用 ListView.getScrollY() 不能很好地恢复滚动位置。
见Android: ListView.getScrollY() - does it work?
指的是整个view的滚动量,所以几乎都是0。
我也经常遇到这个值是 0。 ListView.getFirstVisiblePosition() 与 ListView.setSelection() 更可靠。
【讨论】:
做简单的......
@Override
protected void onPause()
{
index = listView.getFirstVisiblePosition();
// store index using shared preferences
}
和..
@Override
public void onResume() {
super.onResume();
// get index from shared preferences
if(listView != null){
if(listView.getCount() > index)
listView.setSelectionFromTop(index, 0);
else
listView.setSelectionFromTop(0, 0);
}
【讨论】: