• 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 会自动滚动到最后一条。

  • 相关阅读:
    Django学习过程中遇到的问题
    代理工具WebScarab安装(转载)
    MongoDB安装之window版本的安装
    QT打包
    小工具--串口
    多线程--信号量
    关于多线程
    QQ界面及简单操作实现
    udp通信
    char *p = "abc";char p[] = "abc";两者之间的区别
  • 原文地址:https://www.cnblogs.com/zhaoyanjun/p/4508664.html
Copyright © 2020-2023  润新知