如何在 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
更糟糕?
当您想通过软键盘事件滚动到底部时使用此功能:
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);
}
});
scrollView.scrollTo (0, Integer.MAX_VALUE)