Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ListView add items to top without list view scroll [duplicate]

Tags:

I have a listView and I want to add new items to the top of the list view but I dont want list view to scroll its content. I want user to look at the same item as he was looking before new items were added.

This is how I add new items to ListView:

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

and this is addRangeToTop method:

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

this is my 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> 

What I want to do is to load old comments when user scrolls to the top.

Thank you for your help.

like image 959
Harlsten Avatar asked Mar 24 '13 10:03

Harlsten


2 Answers

I have found solution here Retaining position in ListView after calling notifyDataSetChanged

Sorry for duplicate question. The final code is this:

    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); 
like image 99
Harlsten Avatar answered Oct 21 '22 13:10

Harlsten


May be this is what you are looking for:

android:transcriptMode="normal" 

"This makes list automatically scroll to the bottom when a data set change notification is received and only if the last item is already visible on screen." - as quoted here

like image 33
Kamran Ahmed Avatar answered Oct 21 '22 13:10

Kamran Ahmed