2013-03-24 66 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

相關問題