Thread.sleep stopping entire function android

2019-09-09 03:30发布

问题:

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.