用TextView動態顯示檔案內容
阿新 • • 發佈:2019-01-03
1. 設定佈局檔案activity_textview.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/content" android:layout_width="fill_parent" android:layout_height="wrap_content" android:scrollbars="vertical" android:fadeScrollbars="false" /> </LinearLayout>
android:scrollbars="vertical"為TextView設定滾動條,android:fadeScrollbars="false"設定滾動條不隱藏。也可用 ScrollView實現。
另外還要在Activity中呼叫setMovementMethod方法。
2. LogActivity
public class LogActivity extends Activity{ private TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_textview); mTextView = (TextView)findViewById(R.id.content); mTextView.setMovementMethod(ScrollingMovementMethod.getInstance()); new DataThread().start(); } private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { mTextView.setText((String)msg.obj); } }; class DataThread extends Thread{ @Override public void run() { while(true) { try { BufferedReader in = new BufferedReader(new FileReader("/sdcard/log")); String line; StringBuilder sb = new StringBuilder(); while((line = in.readLine()) != null) { sb.append(line+'\n'); } mHandler.sendMessage(mHandler.obtainMessage(0, sb.toString())); in.close(); Thread.sleep(2000); } catch(IOException e){ e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
這裡要不斷的獲取檔案內容更新UI,所以檔案的操作另外開個執行緒執行,利用Hander傳送資料到UI執行緒。