Android 如何实现带滚动条的TextView,在更新文字时自动滚动到最后一行

1、主布局代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.android09.MainActivity"
    tools:ignore="MergeRootFrame" >

    <Button
        android:id="@+id/bt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="点击我" />

    <TextView
        android:id="@+id/tv"
        android:text="哈哈哈哈哈哈我是哈哈哈哈布局文件中放置一个TextView,给它添加scrollbars和fadeScrollbars两个属性"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fadeScrollbars="false"
        android:scrollbars="vertical" />

</LinearLayout>

2、主要代码 :

package com.android09;

import android.app.Activity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    Button button ;
    TextView textView ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById( R.id.bt ) ;
        button.setOnClickListener( new OnClickListener() {

            @Override
            public void onClick(View v) {
                String string = "在Ubuntu中有如下几个文件可以设置环境变量/etc/profile:在登录时,"
                        + "操作系统定制用户环境时使用的第一个文件,此文件为系统的每个用户设置环境信息,当用户第一次登录时,"
                        + "该文件被执行./etc/environment:在登录时操作系统使用的第二个文件,"
                        + "系统在读取你自己的profile前,设置... " ;

                refreshLogView( string );

            }
        });

        textView = (TextView) findViewById( R.id.tv ) ;
        textView.setMovementMethod(ScrollingMovementMethod.getInstance());


    }

    void refreshLogView(String msg){
        textView.append(msg);
        int offset=textView.getLineCount()*textView.getLineHeight();
        if(offset>textView.getHeight()){
            textView.scrollTo(0,offset-textView.getHeight());
        }
    }
}


3、运行效果:

     在给 TextView 添加文字时,textview 会自动滚动到最后一条。

原文地址:https://www.cnblogs.com/zhaoyanjun/p/4508664.html