场景:开发的过程,如果一个页面子View比较多,一个屏幕放不下,此时我们大多会采用ScrollView来实现。然后产品可能会提这种需求,比如某个子View在最底部,产品想要页面进入就直接滑到最底部;或者是当页面滑到最底部时,点击某个按钮直接滑到顶部。
还是先呈上方法,然后再来具体分析
mScrollView.fullScroll(ScrollView.FOCUS_UP);//滑到顶部
mScrollView.fullScroll(ScrollView.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);
}
这里我们可以看到实际上是调用了scrollAndFocus()方法,继续来看源码
/**
* <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;
}
看到这里就很明白了吧,最终是调用doScrollY()这个方法,所以能够实现滑动到顶部或者底部的效果
还没有结束,重点在这里,请仔细看完 - - ->
fullScroll()这个方法不能直接被调用,因为Android中的布局加载需要时间(跟布局的嵌套度以及页面的复杂度等都有关),页面创建不等于view马上就会显示,而是在等待绘制完成,虽然很快,但是如果立即调用fullScroll(),此时view可能还没有完成,这样就会报异常,应该通过handler来调用fullScroll(),具体代码如下:
new Handler().post(new Runnable() {
@Override
public void run() {
mScrollView.fullScroll(ScrollView.FOCUS_UP);//滑到顶部
//mScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滑到底部
}
});