Android 如何?帶捲軸的TextView,在更新文字時自動滾動到最後一行,androidtextview
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 會自動滾動到最後一條。