Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 219
Carl Manaster Avatar asked Jul 22 '10 21:07

Carl Manaster


3 Answers

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);
like image 53
Sergey Avatar answered Nov 16 '22 00:11

Sergey


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.

like image 21
strange-corner Avatar answered Nov 16 '22 00:11

strange-corner


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);
 }
});
like image 26
Alessandro Roaro Avatar answered Nov 16 '22 01:11

Alessandro Roaro