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?
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);
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.
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With