我想要一个ScrollView从底部开始。任何方法吗?


当前回答

我增加工作完美。

    private void sendScroll(){
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {Thread.sleep(100);} catch (InterruptedException e) {}
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.fullScroll(View.FOCUS_DOWN);
                    }
                });
            }
        }).start();
    }

Note

这个答案是一个非常老版本的android的变通方案。今天postDelayed已经没有这个bug了,你应该使用它。

其他回答

当视图尚未加载时,您不能滚动。你可以“稍后”用上面的post或sleep call来做这件事,但这不是很优雅。

最好计划滚动并在下一个onLayout()中执行。示例代码如下:

https://stackoverflow.com/a/10209457/1310343

在Kotlin协程中使用there还有另一种很酷的方法。使用协程而不是具有可运行对象(post/postDelayed)的处理程序的优点是,它不会触发昂贵的线程来执行延迟操作。

launch(UI){
    delay(300)
    scrollView.fullScroll(View.FOCUS_DOWN)
}

将协程的HandlerContext指定为UI是很重要的,否则UI线程可能不会调用延迟的操作。

有人说scrollView。Post没用。

如果你不想用scrollView。postDelayed,另一种选择是使用侦听器。下面是我在另一个用例中所做的:

ViewTreeObserver.OnPreDrawListener viewVisibilityChanged = new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        if (my_view.getVisibility() == View.VISIBLE) {
            scroll_view.smoothScrollTo(0, scroll_view.getHeight());
        }
        return true;
    }
};

你可以这样把它添加到视图中:

my_view.getViewTreeObserver().addOnPreDrawListener(viewVisibilityChanged);

所有答案的组合对我来说很管用:

扩展函数PostDelayed

private fun ScrollView.postDelayed(
    time: Long = 325, // ms
    block: ScrollView.() -> Unit
) {
    postDelayed({block()}, time)
}

扩展函数measureScrollHeight

fun ScrollView.measureScrollHeight(): Int {
    val lastChild = getChildAt(childCount - 1)
    val bottom = lastChild.bottom + paddingBottom
    val delta = bottom - (scrollY+ height)
    return delta
}

扩展函数滚动底部

fun ScrollView.scrollToBottom() {
    postDelayed {
        smoothScrollBy(0, measureScrollHeight())
    }
}

注意,最小延迟应该至少325毫秒,否则滚动将会有bug(不是滚动到整个底部)。当前高度和底部之间的增量越大,延迟时间就应该越大。

我尝试成功了。

scrollView.postDelayed(new Runnable() {
    @Override
    public void run() {
        scrollView.smoothScrollTo(0, scrollView.getHeight());
    }
}, 1000);