[英]How to setText from a separate Thread in Android
我想從一個Thread中setText。
這是我的線程代碼:
private class GenerateThread implements Runnable {
public void run(){
// generate the first music
music = generate(prevmusic, prevmusic.length);
prevmusic = music;
// write the midi
writeMidi(music, song);
textOut.setText("Initialising...");
});
}
}
在我的主要代碼中,我使用
Thread t = new Thread(new GenerateThread());
t.start();
它不允許我從線程中setText。 在互聯網上的一些帖子之后,我嘗試使用處理程序,但這給了我錯誤,我想我是這樣雙重定義Runnable。
處理程序處理程序(主要之前)
private class GenerateThread implements Runnable {
public void run(){
handler.post(new Runnable() {
// generate the first music
music = generate(prevmusic, prevmusic.length);
prevmusic = music;
// write the midi
writeMidi(music, song);
textOut.setText("Initialising...");
});
}
}
如何在線程中設置文本? 謝謝!
除了runOnUiThread
,還有View#post(Runnable)
,我更喜歡這里,因為你不需要看外部Activity( MyActivity.this.runOnUiThread()
)的丑陋外觀。
private class GenerateRunnable implements Runnable {
public void run() {
// this code is executed in a background thread.
// generate the first music
music = generate(prevmusic, prevmusic.length);
prevmusic = music;
// write the midi
writeMidi(music, song);
textOut.post(new Runnable() {
public void run() {
// this code is executed on the UI thread.
textOut.setText("Initialising...");
}
});
}
}
@Override
protected void onResume() {
super.onResume();
new Thread(new GenerateRunnable()).start();
}
也不要混淆Runnable
和Thread
。 Runnable
只是一個帶有run()
方法的普通類。 它可以並且通常在新Thread
上執行。 如果你想要你也可以使GenerateThread
成為一個真正的Thread
如下所示:
private class GenerateThread extends Thread {
@Override
public void run() {
// code here.
}
}
// start somewhere
new GenerateThread().start();
除了使用經典Thread
之外,您還可以考慮使用AsyncTask
因為這完全適用於執行長時間運行並且需要在之后或有進度時更新UI的任務。
只能從UI線程更新UI。 runOnUiThread將允許您在下次執行時在UI線程上運行操作。 你可以這樣做:
runOnUiThread(new Runnable() {
public void run() {
textOut.setText("Initialising...");
}
});
編輯:
private class GenerateThread implements Runnable {
public void run(){
// generate the first music
music = generate(prevmusic, prevmusic.length);
prevmusic = music;
// write the midi
writeMidi(music, song);
// Update the UI
MyActivity.this.runOnUiThread(new Runnable() {
public void run() {
textOut.setText("Initialising...");
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.