java [Android]返回ListView时保存滚动位置

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java [Android]返回ListView时保存滚动位置相关的知识,希望对你有一定的参考价值。

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

/*
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.
*/

以上是关于java [Android]返回ListView时保存滚动位置的主要内容,如果未能解决你的问题,请参考以下文章

ArrayList 对象正在返回 java android 中 ListView 上的一行

Android ListView 返回 Null

返回活动后,Android ListView 不显示传入消息

帮助解决 Android UI ListView 问题

Android - ListView 在到达结束时加载更多项目[关闭]

Android / Java - 如何在 listView 中找到微调器所在的行