等到ListView smoothScrollToPosition()完​​成

时间:2011-10-28 11:50:07

标签: android listview smooth-scrolling

范围

我需要顺利滚动到某个位置,然后使用setSelection(anotherPosition)“跳转”到另一个位置。这样做是为了在ListView中创建(例如)100个项目的平滑滚动的错觉。 smoothScrollToPosition(100)持续时间过长,你知道。

问题

setSelection()不会等到smoothScrollToPositio n完成其工作,因此会立即调用setSelection()并且用户只能看到快速跳转;

代码

private final int scrollableItems = 20;

int firstVisiblePosition = mListView.getFirstVisiblePosition();
if (firstVisiblePosition < scrollableItems) {
    mListView.smoothScrollToPosition(0);
} else {
    mListView.smoothScrollToPosition(firstVisiblePosition - scrollableItems);
    mListView.setSelection(0);
}
mListView.clearFocus();

好的,我们可以改变平滑幻觉的逻辑:首先setSelection(),然后顺利滚动(我们滚动到列表顶部的第一个项目):

    int firstVisiblePosition = mListView.getFirstVisiblePosition();

    if (firstVisiblePosition < scrollableItems) {
        mListView.smoothScrollToPosition(0);
    } else {
        mListView.setSelection(scrollableItems);
        mListView.smoothScrollToPosition(0);
    }
    mListView.clearFocus();

2 个答案:

答案 0 :(得分:24)

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

当然,需要针对您的用例调整滚动等的方向(转到列表顶部)

编辑:如果滚动的速度太高,旧解决方案可能会超调,smoothScrollBy(0,0)将在正确设置选择之前立即停止平滑滚动。

答案 1 :(得分:0)

另一种方法是添加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();