您现在的位置是:首页 > 文章详情

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

日期:2017-05-15点击:307
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://yq.aliyun.com/articles/304090
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章