维护/保存/恢复的滚动位置时,返回到ListView位置、ListView

由网友(烹茶漫卷)分享简介:我有很长的的ListView ,用户可以返回到previous屏幕前,左右滚动。当用户再次打开该的ListView,我要将列表滚动到同一点,这是previously。就如何实现这一目标的任何想法?I have a long ListView that the user can scroll around before...

我有很长的的ListView ,用户可以返回到previous屏幕前,左右滚动。当用户再次打开该的ListView,我要将列表滚动到同一点,这是previously。就如何实现这一目标的任何想法?

I have a long ListView that the user can scroll around before returning to the previous screen. When the user opens this ListView again, I want the list to be scrolled to the same point that it was previously. Any ideas on how to achieve this?

推荐答案

试试这个:

// 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);

说明: ListView.getFirstVisiblePosition()返回顶部可见的列表项。但是,这个项目可以部分地滚出来看,如果要恢复列表的确切滚动位置,你需要得到这个偏移量。因此, ListView.getChildAt(0)返回查看的顶部列表项,然后 View.getTop() - mList.getPaddingTop()返回其相对从 ListView控件的顶偏。然后,恢复的ListView 的滚动位置,我们称之为 ListView.setSelectionFromTop()与项目的索引我们希望和偏移从的ListView的顶部位置的顶部边缘

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.