2012-09-30 121 views
0

只是要清楚,这个问题不是如何从线程更新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行。我究竟做错了什么?

+0

您的活动,而不是在你的线程使用 – Dharmendra

+0

的AsyncTask可避免与runOnUIThread和处理程序或其他难看的代码 – Javanator

回答

2

避免线程,去的AsyncTask

你在找什么is onProgressUpdate(Progress ...),publishProgress(Progress ...) AsyncTask

谷歌为他们的代码示例。

+0

嗯,我不知道它是如何工作的,因为我所做的只是将'Thread'改为'ASyncTask'和'run()'为'execute()'..但它工作正常! – Snailer

1

尝试使用runOnUiThread和更新的TextView里面

+0

可以搞乱创建一个处理程序只从一个活动中调用该方法,而不是一个线程。 – Snailer

0

尝试通过更换onLogAction(定义):

@Override 
public void onLogAction(final String msg) { 
    textView.append(msg); 
} 
+0

哦,对不起,这只是一个错字,这就是我所拥有的。 – Snailer

0

的问题是在这里

NDThread thread = new NDThread(); 
thread.setOnLogActionListener(this); 
thread.run(); 

应该

NDThread thread = new NDThread(); 
thread.setOnLogActionListener(this); 
thread.start(); 

因为“start()方法创建一个新线程,执行的run()方法。 运行()方法只是在当前线程中执行,而不启动新线程。“

也正如其他人提到的,你不需要两个处理程序。只要做到:

public void logAction(final String str) { 
     if(log_listener != null) log_listener.onLogAction(str);   
    } 

,并在主要活动

@Override 
    public void onLogAction(final String msg) { 
     MyActivity.this.runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
      textView.append(msg); 
      } 
     }); 
    }