我正在使用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)
情况:
将适配器设置为列表视图时,它会刷新其状态.因此,通常会自动向上滚动.
解决方案:
将适配器分配给listview(如果没有),否则仅更新分配的适配器的数据集,而不是将其重新设置为listview.
以下链接解释了详细的教程;
祝好运!
| 归档时间: |
|
| 查看次数: |
30776 次 |
| 最近记录: |