如何在Android中编程滚动ScrollView到底部?

3
如何在Android中编程滚动ScrollView到底部?
提供的代码
logScroll.scrollTo(0, logScroll.getBottom());

无法正常工作(滚动到底部时回到了一开始的位置,而不是真正的底部)。

布局如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inthemoon.trylocationlistener.MainActivity">

    <ScrollView
        android:id="@+id/log_scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/log_text"

            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </ScrollView>


</RelativeLayout>

填充代码如下:

@BindView(R.id.log_scroll)
    ScrollView logScroll;

    @BindView(R.id.log_text)
    TextView logText;

    private void log(String msg) {
        logText.append(new SimpleDateFormat( "HH:mm:ss ", Locale.US ).format(new Date()) + msg + "\n");
        logScroll.scrollTo(0, logScroll.getBottom());
    }

更新

我阅读了一些回答并写下:

private void log(String msg) {
        logText.append(new SimpleDateFormat( "HH:mm:ss ", Locale.US ).format(new Date()) + msg + "\n");
        //logScroll.scrollTo(0, logScroll.getBottom());
        logScroll.fullScroll(View.FOCUS_DOWN);
    }

为什么使用post比这更糟糕?

getBottom()是一个View方法。XML的锚点。你想要到达视口的底部吗? - OneCricketeer
3
https://dev59.com/9nA75IYBdhLWcg3w1sv2#4524131 - Sujay
2个回答

18

当您希望在键盘事件下滚动到底部时,请使用此选项:

scrollView.postDelayed(new Runnable() {
    @Override
    public void run() {
         scrollView.fullScroll(ScrollView.FOCUS_DOWN);
    }
}, 100);

并且实现瞬间滚动:

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

0

scrollView.scrollTo(0, Integer.MAX_VALUE)

scrollView.scrollTo(0, Integer.MAX_VALUE)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接