我创建了一个动态ListView,其中从顶部添加对象.
当用户按下按钮时,listView将从数组的内容更新,然后在自定义arrayAdapter上调用notifyDataSetChanged().
现在我想在添加时保留列表位置,所以我添加了这段代码:
// pausedCounter trace the number of objects(lines) to add to the listView
int idx = listView.getFirstVisiblePosition() + pausedCounter;
View first = listView.getChildAt(0);
int position = 0;
if (first != null)
position = first.getTop();
// cycle to add the new objects to the listView
for (Tweet[] tweets1 : pausedTweets)
super.updateTweets(tweets1);
listView.setSelectionFromTop(idx, position);
// reset of counter and accumulator
pausedTweets = new ArrayList<Tweet[]>();
pausedCounter = 0;
Run Code Online (Sandbox Code Playgroud)
此代码以这种方式运行:如果getFirstVisiblePosition返回2,并且pausedCounter为5,则在更新之后,列表将被设置为新五个元素的第3个.
我想要的是将列表的第一个可见元素设置为8.
经过进一步的测试后,我发现listView的子节点数在这段代码的运行过程中没有变化,所以在我调用setSelectionFromTop 后它会更新listView的大小.可能是这个问题?
Mar*_*ele 21
诀窍是:
listView.post(new Runnable() {
@Override
public void run() {
listView.setSelectionFromTop(idx, finalPosition);
}
});
Run Code Online (Sandbox Code Playgroud)
使用post方法允许在更改位置之前等待ListView的更新.
归档时间: |
|
查看次数: |
7499 次 |
最近记录: |