Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Reverse listview as message display

I've got a little question for my Android App. I searched for a long time but found nothing about my problem.

Scenario : I've to display a revert listview (as Facebook Messenger). And when the user scrolls to the top, load more messages.

Problem : After notifiyDataAsChanged() call, the scroll is not the same! I want to conserve exactly the same position as before loading.

I tried that code :

// save index and top position
int index = list.getFirstVisiblePosition()+result.size();
View v = list.getChildAt(index);
int top = (v == null) ? 0 : v.getTop();

// ...
// restore
list.setSelectionFromTop(index, top);

But the scroll is not exactly the same after loading.

Have you got an idea ?

like image 251
Florian Mac Langlade Avatar asked May 01 '13 12:05

Florian Mac Langlade


4 Answers

I think you should look into using TranscriptMode and StackFromBottom with your listview:

android:stackFromBottom="true"
android:transcriptMode="normal"

By setting the transcript mode to normal it will scroll to the bottom only if the last item was already in view. That way your users can view the previous list view items without interruption when you call notifydatasetchanged.

like image 166
jimmithy Avatar answered Nov 05 '22 22:11

jimmithy


For Kotlin is more easy just

 myList.reverse()
like image 28
Gastón Saillén Avatar answered Oct 02 '22 12:10

Gastón Saillén


do like this:

Collections.reverse(YourList); // ADD THIS LINE TO REVERSE ORDER!
YourList.notifyDataSetChanged;
like image 6
Ramon Avatar answered Nov 05 '22 23:11

Ramon


I fixed this by using the same code as you included but I update the index variable by the number of items I add to the adapter before restoring the position. Seems to do the trick.

like image 3
Anders Haglund Avatar answered Nov 06 '22 00:11

Anders Haglund