有没有办法阻止列表视图在其适配器的数据更改时滚动到其顶部位置?

ura*_*dom 20 android

在更改它的适配器数据时,我在保留列表视图的滚动位置时遇到了一些麻烦.

我目前正在做的是在onCreateListFragment中创建一个自定义ArrayAdapter(带有重写的getView方法),然后将其分配给它的列表:

mListAdapter = new CustomListAdapter(getActivity());
mListAdapter.setNotifyOnChange(false);
setListAdapter(mListAdapter);
Run Code Online (Sandbox Code Playgroud)

然后,当我从定期获取一切装载机接收新的数据,我这样做是在其onLoadFinished回调:

mListAdapter.clear();
mListAdapter.addAll(data.items);
mListAdapter.notifyDataSetChanged();
Run Code Online (Sandbox Code Playgroud)

问题是,调用clear()重置listview的滚动位置.删除该调用会保留该位置,但它显然会将旧项目留在列表中.

这样做的正确方法是什么?

Str*_*ton 34

正如您自己指出的那样,调用'clear()'会使位置重置为顶部.

摆弄滚动位置等是让这个工作变得有点蠢蠢欲动.

如果您的CustomListAdapter是ArrayAdapter的子类,则可能是这个问题:

对clear()的调用,调用'notifyDataSetChanged()'.你可以阻止这个:

mListAdapter.setNotifyOnChange(false); // Prevents 'clear()' from clearing/resetting the listview
mListAdapter.clear();
mListAdapter.addAll(data.items);
// note that a call to notifyDataSetChanged() implicitly sets the setNotifyOnChange back to 'true'!
// That's why the call 'setNotifyOnChange(false) should be called first every time (see call before 'clear()').
mListAdapter.notifyDataSetChanged(); 
Run Code Online (Sandbox Code Playgroud)

我自己没试过,但试试看:)


Jar*_*ows 6

签出:返回ListView时保持/保存/恢复滚动位置

在调用.clear(),. addAll()和之前,使用它来保存ListView中的位置.notifyDataSetChanged().

int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
Run Code Online (Sandbox Code Playgroud)

更新ListView适配器后,Listview的项目将被更改,然后设置新的位置:

mList.setSelectionFromTop(index, top);
Run Code Online (Sandbox Code Playgroud)

基本上,您可以保存位置并向后滚动,保存ListView状态或整个应用程序状态.

其他有用的链接:

保存位置: 如何在Android中保存和恢复ListView位置

保存状态: Android ListView y位置

问候,

请让我知道这可不可以帮你!