Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 局部刷新 ScrollView 內容的實作示例

編輯:關於 Android 程式設計

做即時訊息、日誌串流或任何「資料會持續長出來」的畫面時,一定會遇到這個需求:新資料進來,要 append 到 ScrollView 裡,而且畫面最好自動捲到最底部讓使用者看到最新一筆。

這裡的關鍵有兩點:一是定時觸發的機制,二是從子線程安全地更新 UI。示範用一個獨立線程每 5 秒觸發一次,並透過 View 自己的 post() 把更新丟回主線程執行。

一、建立包含 ScrollView 的佈局

版面結構是這樣:ScrollView 裡面放一個 LinearLayout(作為容器),容器裡放一個 TextView(用來 append 文字),另外在 ScrollView 外面放一個結束按鈕。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/exit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Exit" />

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >

        <LinearLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>
    </ScrollView>
</LinearLayout>

二、刷新邏輯實作

package com.example.uirefresh;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

public class MainActivity extends Activity implements View.OnClickListener {

    private Button btnExit;
    private TextView text;
    private ScrollView scroll;
    private boolean bool = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnExit = (Button) findViewById(R.id.exit);
        text    = (TextView) findViewById(R.id.text);
        scroll  = (ScrollView) findViewById(R.id.scroll);

        btnExit.setOnClickListener(this);

        // 在主線程 main 中開一子線程來刷新局部的 ScrollView
        new Thread(new RefreshThread()).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.exit:
                finish();
                break;
        }
    }

    public class RefreshThread implements Runnable {
        @Override
        public void run() {
            while (bool) {
                try {
                    Thread.sleep(5000);   // 每五秒刷新一次
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (this) {
                    // 用 post 方法刷新
                    text.post(new Runnable() {
                        @Override
                        public void run() {
                            text.append("Hello World...\n");
                        }
                    });
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bool = false;   // 讓線程有機會離開迴圈
    }
}

幾個值得注意的細節

為什麼用 post() 而不是直接改 TextView?子線程直接操作 View 會拋出 CalledFromWrongThreadException。View.post(Runnable) 會把 Runnable 丟進該 View 所屬線程的訊息佇列,由主線程取出執行,這是最輕量的線程切換方式。效果等同於 Handler,但少了建立 Handler 的步驟。

bool = false 一定要放在 onDestroy()。否則線程會永遠跑下去,Activity 已經不存在了還在試圖更新 View,這是典型的記憶體洩漏來源。更嚴謹的做法是用 volatile 修飾這個旗標,或者直接用 interrupt() 中斷線程。

為什麼只刷新 TextView 而不是整個 ScrollView?這就是所謂的「局部刷新」。Android 的繪製流程若呼叫 invalidate() 會觸發重新測量與繪製;只針對特定子 View 更新,系統能大幅減少無效的 redraw,這在長清單上差異明顯。範例中 append 文字後 TextView 高度改變,ScrollView 會自動重新計算捲動範圍。

自動捲到底要另外處理。append 內容後 ScrollView 停在原位,不會自己往下跑。若需要自動捲到最新一筆,在 run() 裡補一段:

text.post(new Runnable() {
    @Override
    public void run() {
        text.append("Hello World...\n");
        scroll.fullScroll(View.FOCUS_DOWN);   // 或 scroll.smoothScrollTo(...)
    }
});

延伸建議

這個範例用「定時輪詢 + append 到 TextView」來演示局部刷新的觀念,很容易理解。但如果你要做的是真正的訊息列表,改用 RecyclerView 搭配 ListAdapter 與 DiffUtil 會好得多——它天生支援差異計算與動畫,不必把全部內容塞進一個 TextView,也不必每次重繪整段文字。

另外,用無窮迴圈加 Thread.sleep() 做定時任務,在 Activity 銷毀時需要自己善後。若想更省心,可以改用 Handler.postDelayed() 達到同樣效果,線程與生命週期的管理都更單純:

private final Handler handler = new Handler(Looper.getMainLooper());
private final Runnable ticker = new Runnable() {
    @Override
    public void run() {
        text.append("Hello World...\n");
        handler.postDelayed(this, 5000);
    }
};

// onCreate 中啟動
handler.post(ticker);

// onDestroy 中停止
@Override
protected void onDestroy() {
    super.onDestroy();
    handler.removeCallbacks(ticker);
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved