Thread.sleep停止整个功能android [英] Thread.sleep stopping entire function android

查看:109
本文介绍了Thread.sleep停止整个功能android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个java函数,我想在中间延迟。

  frombox.setText(simpchi [rannum] +\\\
[+ pinyin [rannum] +]);
字符串含义=意义[rannum];
尝试{
Thread.sleep(500);
} catch(InterruptedException e){
Thread.currentThread()。interrupt();
e.printStackTrace();
}
tobox.setText(meaning.replace(/,\\\
));

我希望收件箱的文本发生变化,然后在0.5秒后更改收件箱的文本。 p>

但是,执行此操作时,整个函数会延迟,然后同时将收件箱和收件箱的文本更改。



我在做什么错了?对不起,如果这真的很简单,我对Java很陌生。

解决方案

您不应该调用 Thread.sleep()在UI线程中。 不要!
您应该做什么:

  Handler handler = new Handler(); 
handler.postDelayed(new Runnable(){
public void run(){
tobox.setText(meaning.replace(/,\\\
));
}
},500); // 500 ms

或简单地(Credits to zapl) p>

  tobox.postDelayed(new Runnable(){
public void run(){
tobox.setText .replace(/,\\\
));
}
},500); // 500 ms

通过这种方式,第二个settext将被延迟并在UI线程中运行。 / p>

I have a java function that I want to delay in the middle.

frombox.setText(simpchi[rannum] + "\n[" + pinyin[rannum] + "]");
String meaning = meanings[rannum];
try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        e.printStackTrace();
    }
tobox.setText(meaning.replace("/", "\n"));

I want the frombox's text to change, then after 0.5 seconds, the tobox's text to change.

However, when executing this, the entire function delays, then the frombox and tobox's text changes at the same time.

What am I doing wrong? Sorry if this is really simple; I'm very new to java.

解决方案

You shouldn't call Thread.sleep() in the UI thread. Never! What you should do:

Handler handler = new Handler();
handler.postDelayed(new Runnable(){ 
    public void run(){
        tobox.setText(meaning.replace("/", "\n"));
    }
}, 500); // 500 ms

or simply (Credits to zapl):

tobox.postDelayed(new Runnable(){ 
    public void run(){
        tobox.setText(meaning.replace("/", "\n"));
    }
}, 500); // 500 ms

This way the 2nd settext will be delayed and also ran in the UI thread.

这篇关于Thread.sleep停止整个功能android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆