Carl Manaster
Carl Manaster

Reputation: 40356

Setting ListView scroll position nicely in Android

I am aware of setSelection(), setSelectionFromTop(), and setSelectionAfterHeaderView(), but none of them seems to do what I want.

Given an item in the list, I want to scroll so that it is in view. If the item is above the visible window of the list, I want to scroll until the item is the first visible item in the list; if the item is below the visible window, I want it to scroll up until it is the last visible item in the list. If the item is already visible, I don't want any scrolling to occur.

How do I go about this?

Upvotes: 9

Views: 24619

Answers (4)

foshoshin
foshoshin

Reputation: 176

A better solution to Sergey's answer is to call setSelection() later in the Activity/Fragment life cycle, perhaps in onStart(). That way, you have a guarantee that the View is ready rather than using some arbitrary delay.

Upvotes: 0

Alessandro Roaro
Alessandro Roaro

Reputation: 4733

Sergey's answer works, but I believe that the right way of doing this is setting up an observer to be notified when the ListView has been created.

listView.getViewTreeObserver().addOnGlobalLayoutListener(
     new ViewTreeObserver.OnGlobalLayoutListener() {
 @Override
 public void onGlobalLayout() {
     scrollTo(scrollToPosition);
     listView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
 }
});

Upvotes: 3

strange-corner
strange-corner

Reputation: 476

I think, I was looking for the same, then I found the following solution:

if (listview.getFirstVisiblePosition() > pos 
    || listview.getLastVisiblePosition() <= pos) {
    listview.smoothScrollToPosition(pos);
}

API 8 is required to use smoothScrollToPosition (which is a reasonable minimum anyways) so you are aware.

Upvotes: 4

Sergey
Sergey

Reputation: 389

It occurs because listView isn't created yet. Try to post runnable such as:

getListView().postDelayed(new Runnable() {          
    @Override
    public void run() {
        lst.setSelection(15);
    }
},100L);

Upvotes: 15

Related Questions