Android – TextView(二)追加文字,并自动滚动(触底时)
**实现要求:**在固定高度的TextView内追加显示内容,当内容高度超出TextView高度时,内容自动向上滚动(能显示最下方内容)。
布局:
<!--最后三个属性很重要-->
<TextView
android:id="@+id/tvLog"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:enabled="false"
android:focusable="false"
android:gravity="center_vertical|top"
android:inputType="textMultiLine"
android:scrollbars="vertical"
android:scrollbarStyle="insideOverlay"
android:fadeScrollbars="false"
android:scrollbarFadeDuration="2000">
</TextView>
自定义方法:
private TextView tvLog;
tvLog = findViewById(R.id.tvLog);
tvLog.setMovementMethod(ScrollingMovementMethod.getInstance());
//当需追加新内容时,直接调用此方法即可;
public void addLog(final String strLog) {
final String strText = strLog;
runOnUiThread(new Runnable() {
@Override
public void run() {
//附加与log前的时间标签(可注释)
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
String strDate = formatter.format(curDate);
//已有的log
String strLogs = tvLog.getText().toString().trim();
if (strLogs.equals("")) {
strLogs = strDate + ": " + strText;
} else {
strLogs += "\r\n" + strDate + ": " + strText;
}
//刷新添加新的log
tvLog.setText(strLogs);
//==================add auto scroll========================
//log View自动滚动
tvLog.post(new Runnable() {
@Override
public void run() {
int scrollAmount = tvLog.getLayout().getLineTop(tvLog.getLineCount()) - tvLog.getHeight();
if (scrollAmount > 0)
tvLog.scrollTo(0, scrollAmount);
else
tvLog.scrollTo(0, 0);
}
});
}
});
}
参考:https://blog.csdn.net/u014341735/article/details/78425437