Thread.sleep stopping entire function android

拥有回忆 提交于 2019-12-13 04:51:02

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/20443828/thread-sleep-stopping-entire-function-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!