[英]How to scroll ScrollView to bottom programmatically in Android?
如何在 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.