只是要清楚,這個問題不是如何從線程更新TextView,這工作正常。問題是,即使我在多個線程中進行多次調用來更新TextView,更新僅在線程完成工作後纔會出現。這裏有一個例子:在多線程進程中更新TextView
public class NDThread extends Thread { protected LogActionListener log_listener; private Handler handler = new Handler(); public void run() { logAction("starting"); // Do many things.. logAction("halfway"); // Many more things.. logAction("done"); } public interface LogActionListener { public void onLogAction(String paramString); } public void logAction(final String str) { if(log_listener != null) handler.post(new Runnable() { @Override public void run() { log_listener.onLogAction(str); } }); } }
而且在我的主要活動中,我實現LogActionListener
以收到的字符串和更新的TextView:
NDThread thread = new NDThread(); thread.setOnLogActionListener(this); thread.run(); // Elsewhere.. @Override public void onLogAction(final String msg) { handler.post(new Runnable() { @Override public void run() { textView.append(msg); } }); }
正如你所看到的,我已經在使用Handler
小號兩種線程和活動,因爲我不確定哪個是正確的使用。但是,對於整個Thread來說,結果始終是一個空白的TextView,最後它將打印3行。我究竟做錯了什麼?
您的活動,而不是在你的線程使用 – Dharmendra
的AsyncTask可避免與runOnUIThread和處理程序或其他難看的代碼 – Javanator