2012-09-30 124 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); 
      } 
     }); 
    }