Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android ScrollView 快速滾動到底部的方法

編輯:關於 Android 程式設計

其實只要一行程式碼就能搞定:

mScrollView.fullScroll(ScrollView.FOCUS_DOWN);

原始碼中實現該功能的兩個關鍵方法如下。

首先是 fullScroll:

public boolean fullScroll(int direction) {
    boolean down = direction == View.FOCUS_DOWN;
    int height = getHeight();
    mTempRect.top = 0;
    mTempRect.bottom = height;
    if (down) {
        int count = getChildCount();
        if (count > 0) {
            View view = getChildAt(count - 1);
            mTempRect.bottom = view.getBottom() + mPaddingBottom;
            mTempRect.top = mTempRect.bottom - height;
        }
    }
    return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
}

接著是 scrollAndFocus:

private boolean scrollAndFocus(int direction, int top, int bottom) {
    boolean handled = true;
    int height = getHeight();
    int containerTop = getScrollY();
    int containerBottom = containerTop + height;
    boolean up = direction == View.FOCUS_UP;
    View newFocused = findFocusableViewInBounds(up, top, bottom);
    if (newFocused == null) {
        newFocused = this;
    }
    if (top >= containerTop && bottom <= containerBottom) {
        handled = false;
    } else {
        int delta = up ? (top - containerTop) : (bottom - containerBottom);
        doScrollY(delta);
    }
    if (newFocused != findFocus()) newFocused.requestFocus(direction);
    return handled;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved