我有一个很长的ListView
,用户可以在返回到前一个屏幕之前滚动.当用户再次打开此ListView
时,我希望列表滚动到与以前相同的位置.对如何实现这一点有什么 idea 吗?
我有一个很长的ListView
,用户可以在返回到前一个屏幕之前滚动.当用户再次打开此ListView
时,我希望列表滚动到与以前相同的位置.对如何实现这一点有什么 idea 吗?
试试这个:
// save index and top position
int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());
// ...
// restore index and position
mList.setSelectionFromTop(index, top);
Explanation:
ListView.getFirstVisiblePosition()
returns the top visible list item. But this item may be partially scrolled out of view, and if you want to restore the exact scroll position of the list you need to get this offset. So ListView.getChildAt(0)
returns the View
for the top list item, and then View.getTop() - mList.getPaddingTop()
returns its relative offset from the top of the ListView
. Then, to restore the ListView
's scroll position, we call ListView.setSelectionFromTop()
with the index of the item we want and an offset to position its top edge from the top of the ListView
.