1. TextView
1.1 設置TextView可滾動且更新文字後自動滾動至最後一行
【方案】如下步驟
① 在TextView佈局文件中給TextView加入如下屬性
android:scrollbars="vertical"
android:fadeScrollbars="false"
② 在Activity中的onCreate()方法中,使用setMovementMethod(MovementMethod movement)方法配置TextView的滾動方式。
TextView tv = (TextView) findViewById(R.id.tv_log);
tv.setMovementMethod(ScrollingMovementMethod.getInstance());
③ 更新文字時,使用View.scrollTo(int x,int y)方法使其自動滾動到最後一行。
private void printLog(String log) {
tv.append("\n" + log);
// 計算偏移量
int offset = tv.getLayout().getLineTop(tv.getLineCount()) + tv.getCompoundPaddingTop() + tv.getCompoundPaddingBottom();
// 滾動到目標定位點
if (offset > tv.getHeight()) {
tv.scrollTo(0, offset - tv.getHeight());
}
}
【參考1】https://www.jianshu.com/p/01d9b4564908 # Android 如何實現帶滾動條的TextView,在更新文字時自動滾動到最後一行?
【參考2】https://stackoverflow.com/questions/34248301/textview-getlinecountgetlineheight-getheight# # TextView getLineCount()*getLineHeight() != getHeight()