1. 程式人生 > >Android 如何實現帶滾動條的TextView,在更新文字時自動滾動到最後一行?

Android 如何實現帶滾動條的TextView,在更新文字時自動滾動到最後一行?

如下設定:滾動條為垂直滾動條,並且一直可見(當TextView中的文字行數超過頁面能顯示的範圍之後)。

android:scrollbars="vertical"        
android:fadeScrollbars
="false"

2、在Activity中的onCreate()方法中,使用setMovementMethod(MovementMethod movement)方法配置TextView的滾動方式。

1 final TextView logView=(TextView)findViewById(R.id.logView);
2 logView.setMovementMethod(ScrollingMovementMethod.getInstance());

3、更新文字時,使用View的scrollTo(int x,int y)方法使其自動滾動到最後一行。

複製程式碼
1 void refreshLogView(String msg){
2    logView.append(msg);
3    int offset=logView.getLineCount()*logView.getLineHeight();
4    if(offset>logView.getHeight()){
5        logView.scrollTo(0,offset-logView.getHeight());
6    }
7 }