gpt4 book ai didi

java - 如何从 Android 中的单独线程设置文本

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:31:12 25 4
gpt4 key购买 nike

我想在线程中设置文本。

这是我的线程代码:

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();

它不允许我从线程内设置文本。按照互联网上的一些帖子,我尝试使用处理程序,但这给了我错误,我认为我以这种方式双重定义了 Runnable。

处理程序处理程序(在 main 之前)

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();
}

也不要混淆 RunnableThreadRunnable 只是一个带有 run() 方法的普通类。它可以并且经常在新的 Thread 上执行。如果你愿意,你也可以使 GenerateThread 成为真正的 Thread,如下所示:

private class GenerateThread extends Thread {
@Override
public void run() {
// code here.
}
}
// start somewhere
new GenerateThread().start();

除了使用经典的 Thread 之外,您还可以考虑使用 AsyncTask,因为它专为长时间运行的任务而设计,需要在之后或何时更新 UI有进步。

关于java - 如何从 Android 中的单独线程设置文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12478600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com