Wait unitl ListView's smoothScrollToPosition() finishes

前端 未结 2 1691
灰色年华
灰色年华 2020-12-28 18:15

Scope

I need to scroll to certain position smoothly and then "jump" to another position with setSelection(anotherPosition). This is done to c

相关标签:
2条回答
  • 2020-12-28 18:48
    final ListView listView = ...;
    View listItemView = ...;
    listView.smoothScrollBy(listItemView.getHeight() * NUMBER_OF_VIEWS, 
        DURATION * 2);
    listView.postDelayed(new Runnable() {
        public void run() {
            listView.smoothScrollBy(0, 0); // Stops the listview from overshooting.
            listView.setSelection(0);
        }
    }, DURATION);
    

    Of course, direction of the scroll etc. would need to be adjusted for your use case (go to the top of the list)

    EDIT: Old solution could overshoot if the velocity of the scroll was too high, smoothScrollBy(0,0) will stop the smooth scrolling before setting the selection properly and immediately.

    0 讨论(0)
  • 2020-12-28 18:54

    Another way is to add an OnScrollListener.

    private final int scrollableItems = 20;
    
    int firstVisiblePosition = mListView.getFirstVisiblePosition();
    if (firstVisiblePosition < scrollableItems) {
        mListView.smoothScrollToPosition(0);
    } else {
    
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
          @Override
          public void onScrollStateChanged(AbsListView absListView, int i) {
            if (i == SCROLL_STATE_IDLE) {
              mListView.setSelection(0);
               }
          }
       })
    
       mListView.smoothScrollToPosition(firstVisiblePosition - scrollableItems);
    }
    mListView.clearFocus();
    
    0 讨论(0)
提交回复
热议问题