Android scroll to the bottom of a listview

2019-02-08 17:00发布

问题:

this is not a repeat of another question.. it's more an expansion. I hope :)

I've a list view with a few hundred items in it.. They are date stamped entries in another view.

When I show the screen I want it to scroll to the bottom, so the most recent items are displayed, but in a logical "end of the thing" sort of way.

m_list.setSelection(m_list.getCount()-1);

Kewl as... but :( Now my list won't scroll. It seem stuck on the bottom. I can see the "truck" and it's tiny and at the bottom.

Ok.. so my questy is thus.. How do I start off by scrolling to the bottom, but still allow the user (me) to scroll up when they (me again) want to scroll up.

回答1:

set the following on your listview in the XML.

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


回答2:

You can use following code to reach at bottom of list view.

listView.postDelayed(new Runnable() {
        @Override
        public void run() {
            listView.setSelection(listView.getCount());
        }
    }, 500);

This will set delay of 500 ms. Or you can use

listView.post(new Runnable() {
        @Override
        public void run() {
            listView.setSelection(listView.getCount());
        }
    });

This will scroll your list view pragmatically.