开发者

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?


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);
 }
});


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜