只是要清楚,这个问题不是如何从线程更新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