ScrollView手动滑动到屏幕底部,fullScroll

司空玮
2023-12-01
需求场景:
嵌套了ScrollView,在底部代码设置VIew显示,但是不会滑动出来,所以就必须代码自动把ScrollView内容滑动出来。
解决:

scrollView有一个fullScroll方法,

mScrollView.fullScroll(ScrollView.FOCUS_DOWN);滚动到底部

mScrollView.fullScroll(ScrollView.FOCUS_UP);滚动到顶部

但是,这个方法不能直接调用,Android很多函数都是基于消息队列来同步,所以需要一部操作,
addView完之后或者让某个view显示之后,不等于马上就会显示,而是在队列中等待处理,虽然很快,但是如果立即调用fullScroll, view可能还没有显示出来,所以会滑动失败。

 mScrollView.post(new Runnable() {
          @Override
        public void run() {
            mScrollView.fullScroll(View.FOCUS_DOWN);
          }
       });

不过在看源码的时候,还会发现 有一个pageScroll方法,参数和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>
      */
    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>Handles scrolling in response to a "page up/down" shortcut press. This
     * method will scroll the view by one page up or down 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>
     */
    public boolean pageScroll(int direction) {
      boolean down = direction == View.FOCUS_DOWN;
        int height = getHeight();
        if (down) {
            mTempRect.top = getScrollY() + height;
            int count = getChildCount();
            if (count > 0) {
                View view = getChildAt(count - 1);
                if (mTempRect.top + height > view.getBottom()) {
                    mTempRect.top = view.getBottom() - height;
                }
            }
        } else {
            mTempRect.top = getScrollY() - height;
            if (mTempRect.top < 0) {
                mTempRect.top = 0;
            }
        }
        mTempRect.bottom = mTempRect.top + height;
        return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
  }










 类似资料: