2013-03-24 65 views
22

我有一个listView,我想添加新项目到列表视图的顶部,但我不希望列表视图滚动其内容。我希望用户在添加新项目之前查看与他相同的项目。Android ListView将项目添加到顶部,无列表视图滚动

这是我如何增加新项目的ListView:

this.commentsListViewAdapter.addRangeToTop(comments); 
this.commentsListViewAdapter.notifyDataSetChanged(); 

,这是addRangeToTop方法:

public void addRangeToTop(ArrayList<Comment> comments) 
{ 
    for (Comment comment : comments) 
    { 
     this.insert(comment, 0);   
    } 
} 

这是我的ListView:

<ListView 
    android:id="@+id/CommentsListView" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_above="@+id/AddCommentLayout" 
    android:stackFromBottom="true" >   
</ListView> 

我想什么做的是当用户滚动到顶部时加载旧评论。

谢谢你的帮助。

回答

30

我发现这里Retaining position in ListView after calling notifyDataSetChanged

对不起重复的问题的解决方案。 最后的代码是这样的:

int index = this.commentsListView.getFirstVisiblePosition() + comments.size(); 
    View v = this.commentsListView.getChildAt(commentsListView.getHeaderViewsCount()); 
    int top = (v == null) ? 0 : v.getTop();   

    this.commentsListViewAdapter.AddRangeToTop(comments); 
    this.commentsListViewAdapter.notifyDataSetChanged();  

    this.commentsListView.setSelectionFromTop(index, top); 
+0

非常感谢! – sirvon 2014-10-06 23:55:54

+1

好的解决方法,谢谢! – 2015-03-19 15:03:47

2

也看看ListView的方法public void setSelection (int position)。添加新评论并通知您的适配器后,您可以使用它来保持当前选择的项目。

// Get the current selected index 
int previousSelectedIndex = yourListView.getSelectedItemPosition(); 

// Change your adapter 
this.commentsListViewAdapter.AddRangeToTop(comments); 
this.commentsListViewAdapter.notifyDataSetChanged(); 


// Determine how many elements you just inserted 
int numberOfInsertedItems = comments.size(); 

// Update the selected position 
yourListView.setSelection(previousSelectedIndex + numberOfInsertedItems); 

注:代码未经测试。祝你好运

+0

谢谢你,这个工作不知何故,但不是很好。它滚动两个项目。我认为这是因为列表视图不按项目滚动,而是按像素滚动,并且setSelection完全滚动到该项目。 – Harlsten 2013-03-24 11:13:41

9

可能这是你在找什么:

android:transcriptMode="normal" 

“这使得列表会自动滚动至底部,当接收到的数据集更改通知和仅如果最后一个项目已经可以在屏幕上看到。“ - 如引用here

+1

这个答案应该标记为正确的。 – 2015-12-24 16:39:08

相关问题