android 将ScrollView滚动到底部

方案1:使用 scrollTo 或 smoothScrollTo 滚动到 scrollview 最后一个节点位置

public static void scrollToBottom(final View scroll, final View inner) {
    Handler handler = new Handler();
    handler.post(new Runnable() {
        public void run() {
            int offset = inner.getMeasuredHeight() - scroll.getHeight();
            if (offset < 0) {
                offset = 0;
            }
            scroll.scrollTo(0, offset);
        }
    });
}

方案2(如scrollview中元素还未加载完全就调用,滚动到底部会失败。推荐使用方案3):

scrollView.post(new Runnable() {
    public void run() {
        scrollView.fullScroll(View.FOCUS_DOWN);
    }
});

方案3:

scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        scrollView.post(new Runnable() {
            public void run() {
                scrollView.fullScroll(View.FOCUS_DOWN);
            }
        });
    }
});

 

posted @ 2020-11-01 12:49  乱炖er  阅读(2452)  评论(0编辑  收藏  举报