(從我的答案複製:smoothScrollToPositionFromTop() is not always working like it should)
這是一個已知的bug。見https://code.google.com/p/android/issues/detail?id=36062
不過,我實現了這個解決方法與可能發生的所有邊緣案件涉及:
第一次調用smothScrollToPositionFromTop(position)
,然後當滾動完成,調用setSelection(position)
。後者通過直接跳轉到所需的位置來糾正不完整的滾動。這樣做的用戶仍然有這樣的印象,即它正在被動畫滾動到這個位置。
我實現了兩個輔助方法中這種解決方法:
smoothScrollToPosition()
public static void smoothScrollToPosition(final AbsListView view, final int position) {
View child = getChildAtPosition(view, position);
// There's no need to scroll if child is already at top or view is already scrolled to its end
if ((child != null) && ((child.getTop() == 0) || ((child.getTop() > 0) && !view.canScrollVertically(1)))) {
return;
}
view.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(final AbsListView view, final int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
view.setOnScrollListener(null);
// Fix for scrolling bug
new Handler().post(new Runnable() {
@Override
public void run() {
view.setSelection(position);
}
});
}
}
@Override
public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount,
final int totalItemCount) { }
});
// Perform scrolling to position
new Handler().post(new Runnable() {
@Override
public void run() {
view.smoothScrollToPositionFromTop(position, 0);
}
});
}
getChildAtPosition()
public static View getChildAtPosition(final AdapterView view, final int position) {
final int index = position - view.getFirstVisiblePosition();
if ((index >= 0) && (index < view.getChildCount())) {
return view.getChildAt(index);
} else {
return null;
}
}
這種方法從來沒有爲我工作。 – 2012-07-11 14:31:07
已知錯誤:請參閱回答https://stackoverflow.com/questions/14479078/smoothscrolltopositionfromtop-is-not-always-working-like-it-should/20997828#20997828 – 2014-08-22 14:00:23