[英]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.