您的位置:首页 > 移动开发 > Android开发

ScrollView滚动到底部使用的scrollTo和fullScroll方法的异同

2015-10-22 22:25 405 查看
scrollTo和fullScroll两个方法经常被用来做滚动到底部的操作

不过就这个功能而言 也是有不同之处的

使用fullScroll滚动到底部 使用的参数为 FOCUS_DOWN 顾名思义 和 焦点有关

fullScroll 代码如下

/**
* <p>Handles scrolling in response to a "home/end" shortcut press. This
* method will scroll the view to the top or bottom and give the focus
* to the topmost/bottommost component in the new visible area. If no
* component is a good candidate for focus, this scrollview reclaims the
* focus.</p>
*
* @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
*                  to go the top of the view or
*                  {@link android.view.View#FOCUS_DOWN} to go the bottom
* @return true if the key event is consumed by this method, false otherwise
*/
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);
}

/**
* <p>Scrolls the view to make the area defined by <code>top</code> and
* <code>bottom</code> visible. This method attempts to give the focus
* to a component visible in this area. If no component can be focused in
* the new visible area, the focus is reclaimed by this ScrollView.</p>
*
* @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
*                  to go upward, {@link android.view.View#FOCUS_DOWN} to downward
* @param top       the top offset of the new area to be made visible
* @param bottom    the bottom offset of the new area to be made visible
* @return true if the key event is consumed by this method, false otherwise
*/
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;
}


可以看到 fullScroll将视图滚动到底部 同时焦点作出了改变

scrollTo方法 只执行移动至某位置 不对其他属性作出修改

因此 使用 fullScroll 来执行滚动到底部时 需注意 此时你的UI焦点已经发生变化 且 底部UI无法获得焦点时 此方法无效
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android api