调用notifyDataSetChanged后,在ListView中保留位置

Sea*_*eil 42 android listview

我正在使用OnScrollListener在用户滚动到底部时动态地将项添加到ListView.在我将数据添加到适配器并调用notifyDataSetChanged后,ListView返回到顶部.理想情况下,我想保留ListView中的位置.关于我应该怎么做的任何想法?

iCa*_*arp 97

这可能是你想要的吗?

// save index and top position
int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();

// notify dataset changed or re-assign adapter here

// restore the position of listview
mList.setSelectionFromTop(index, top);
Run Code Online (Sandbox Code Playgroud)

编辑28/09/2017:

自2015年以来,API发生了很大的变化.它类似,但现在它将是:

// save index and top position
int index = mList.FirstVisiblePosition; //This changed
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : v.Top; //this changed

// notify dataset changed or re-assign adapter here

// restore the position of listview
mList.setSelectionFromTop(index, top);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.如果要在不看到更新的情况下将项添加到列表顶部,则需要添加添加到索引int中的项数.int index = mList.getFirstVisiblePosition()+ NUMBER_OF_ADDED_ITEMS; (8认同)
  • 如果setSelection在调用notifyDataSetChanged后不能立即工作,这里有一个解决方法:getListView().postDelayed(new Runnable(){@ Overver public void run(){getListView().setSelection(8);}},500); Android错误据称已分配,因此应在某些时候修复:https://code.google.com/p/android/issues/detail?id = 6744 (5认同)
  • 工作完美.此外,它帮助其他人,这对我来说一开始并不起作用.直到我意识到我之前的一些无限智慧,我添加了`lv.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL)`.不要这样做......它会强行滚动到列表视图的底部,直到你把大部分头发拉出来.哈. (4认同)
  • 我使用getScrollX()和setScrollX()而不是getFirstVisiblePosition()和setSelectionFromTop(),因为在添加内容时仍然会引起一些小的跳转. (2认同)

Tan*_*ner 6

情况:

将适配器设置为列表视图时,它会刷新其状态.因此,通常会自动向上滚动.

解决方案:

将适配器分配给listview(如果没有),否则仅更新分配的适配器的数据集,而不是将其重新设置为listview.

以下链接解释了详细的教程;

Android ListView:刷新时保持滚动位置

祝好运!


归档时间:

查看次数:

30776 次

最近记录:

6 年,10 月 前