-
XML 布局文件
将 TextView 包裹在 ScrollView 中,并确保布局参数正确:<ScrollView android:id="@+id/scrollView" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollbars="vertical" android:textSize="16sp"/> </ScrollView>
-
在 Activity 或 Fragment 中实现逻辑
初始化控件并动态追加文本,确保自动滚动到底部:public class MainActivity extends AppCompatActivity { private TextView textView; private ScrollView scrollView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); scrollView = findViewById(R.id.scrollView); textView.setMaxLines(1000); // 限制最大行数 // 模拟动态追加文本(例如按钮点击或定时任务) Button appendButton = findViewById(R.id.appendButton); appendButton.setOnClickListener(v -> appendText("New text added at: " + System.currentTimeMillis() + "\n")); } // 追加文本并滚动到底部 private void appendText(String newText) { textView.append(newText); scrollToBottom(); } // 确保滚动到底部 private void scrollToBottom() { scrollView.post(() -> scrollView.fullScroll(ScrollView.FOCUS_DOWN)); } }
-
关键点解析
3.1. 布局结构
ScrollView 包裹 TextView,TextView 的高度设为 wrap_content 以允许内容扩展。3.2. 动态追加文本
使用 textView.append() 方法追加新内容,保留已有文本。3.3. 自动滚动到底部
通过 fullScroll(ScrollView.FOCUS_DOWN) 实现滚动,使用 post() 确保在布局更新后执行。
03-02