49

After calling notifydatasetchanged(); I want to scroll to the bottom of list so that user see the last record in the Listview.

(I am writing Chat module so for that purpose I need latest record at the bottom of list to be visible)

Can any one guide me how to achieve this?

ben75
  • 29,217
  • 10
  • 88
  • 134
UMAR-MOBITSOLUTIONS
  • 77,236
  • 95
  • 209
  • 278

3 Answers3

83

I know that this has been answered and you took the answer and it was more than a year ago. But a better way to do this is Transcript Mode. For a demo, see the Android API Demo under Views > Lists > Transcript.

You would set the following on your list view in the XML.

android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"

It will always work whenever you call notifyDataSetChanged(). You can set android:transcriptMode to normal instead if you want an even better result for chat applications: it will scroll to the bottom only if the last item was already in view. That way your users can view the previous chat without interruption when other users chat.

JJD
  • 50,076
  • 60
  • 203
  • 339
Ribose
  • 2,223
  • 16
  • 22
77

Try

listView.post(new Runnable(){
  public void run() {
    listView.setSelection(listView.getCount() - 1);
  }});

The 'post' seems to be required sometime in my experience, particularly if you have very recently updated the list.

Jim Blackler
  • 22,946
  • 12
  • 85
  • 101
  • 1
    this works great. I tried `android:stackFromBottom="true"` before and the problem then is that if there was only a single element in my list view that it would be a the bottom of the screen. Thanks – philipp May 01 '12 at 22:27
  • Note: if the height of the last element is bigger than the height of the listview, the top of the last element will be aligned among the top of the list, i.e. the bottom of the element wont be visible. That's why the stackFromBottom solution is described by Ribose is better for chat-like functionality. – kar Feb 06 '13 at 12:24
  • Worked like a charm! I also tried stackFromBottom="true" but since I was not clearing the list it didn't work for my situation. (At least I think that is why.) – BostonGeorge Nov 24 '13 at 20:52
  • You're right, the `post` is necessary if this is called directly after `notifyDataSetChanged()`. Using `post` postpones the `setSelection()` until the update/refresh of the list is completed. – Ridcully Nov 18 '14 at 12:22
2

I know its very late to answer but may be it will help someone. Using android:transcriptMode="alwaysScroll" will force the listview to scroll to bottom (as here we have used android:stackFromBottom="true") even if you'll try to scroll top which usually required most of the time. So instead of android:transcriptMode="alwaysScroll you can use android:transcriptMode="normal which will behave similar to the requirement of chat app and will not force the list of scroll always if the user want to see the content at the top.

Toppers
  • 559
  • 3
  • 11