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 會自動滾動到最后一條。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM