Java Android应用程序,每秒生成随机单词并在屏幕上显示
我如何制作一个每1秒生成一个随机单词的android应用程序? 这是我的密码:Java Android应用程序,每秒生成随机单词并在屏幕上显示,java,android,Java,Android,我如何制作一个每1秒生成一个随机单词的android应用程序? 这是我的密码: new Timer().scheduleAtFixedRate(new TimerTask(){ public void run() { started = true; word = ""; for (int i = 0; i < lenght+1; i++) { int j
new Timer().scheduleAtFixedRate(new TimerTask(){
public void run()
{
started = true;
word = "";
for (int i = 0; i < lenght+1; i++)
{
int j = rand.nextInt((max-min) + 1) + min;
word += tr.Translate(j);
}
txt.setText(word);
}
}, 0, 5000);
new Timer().scheduleAtFixedRate(new TimerTask()){
公开募捐
{
开始=真;
单词=”;
对于(int i=0;i
似乎每次我的应用程序必须更改文本视图(“txt”)的文本时都会停止;我怎样才能使它工作?毫无疑问,在
线程中运行它。这样做,它将在后台生成单词,一旦已经生成,主UI线程必须将内容附加到txt
实例
new Thread(
new Runnable() {
public void run() {
// your stuff
}
}
).start()
要将结果分配给txt
对象,您可能无法在此线程中执行此操作。为此,您需要在活动中声明一个处理程序
,并在线程中使用该处理程序,因此它对主活动使用sendMessage()
,而活动只设置文本
更多关于这个和
----编辑---
正如@FD_uu所说,还有另一种方法可以在不使用处理程序的情况下进行更新。您只需要调用runOnUiThread()
方法,如下所示:
runOnUiThread(new Runnable() {
public void run() {
txt.setText(your_new_text);
}
});
另一种方法是使用AsyncTask
,这是(含糊其辞地说)线程的“进化”,它为您带来了很多东西。有关AsyncTask
s的详细信息
----编辑---
这将是以下方式之一:
new Thread(
new Runnable() {
public void run() {
new Timer().scheduleAtFixedRate(new TimerTask() {
public void run() {
started = true;
word = "";
for (int i = 0; i < lenght+1; i++)
{
int j = rand.nextInt((max-min) + 1) + min;
word += tr.Translate(j);
}
// This will update your txt instance without the need of a Handler
runOnUiThread(new Runnable() {
public void run() {
txt.setText(word);
}
});
}
}, 0, 5000);
}
}).start();
新线程(
新的Runnable(){
公开募捐{
新计时器().scheduleAtFixedRate(新计时器任务()){
公开募捐{
开始=真;
单词=”;
对于(int i=0;i
试试这个:
int i = 0;
public void changeString() {
started = true;
word = "";
int j = rand.nextInt((max - min) + 1) + min;
word += tr.Translate(j);
txt.setText(word);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (i < lenght + 1) {
changeString();
i++;
}
}
}, 1000);
}
试试上面的方法。你犯的错误是在运行中使用for循环,而不是使用循环运行方法本身。你想要随机实词吗?或者任何字符序列,即使它没有意义?任何字符序列,即使它没有意义。你现在的问题是什么?无法更新文本视图或无法生成文字?无法更新文本视图,因为应用程序在必须更新文本视图时崩溃。我建议使用runOnUiThread()
而不是处理程序。不要使用AsyncTask
进行定时操作。
int i=0;
new Timer().scheduleAtFixedRate(new TimerTask(){
public void run()
{
started = true;
word = "";
int j = rand.nextInt((max-min) + 1) + min;
word += tr.Translate(j);
txt.setText(word);
i++
}
}, 0, 5000);