-1

I want to set "First" word to TextView (textTT) and wait for a while set to "Second" to same TextView but result is directly set "second" to TextView but I need firstly set "First". How can I overcome this? <>

private void applicationTest()  {
    textTT.setText("First");
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    textTT.setText("Second");
}
OmerK
  • 1
  • 1

3 Answers3

2

If you call Thread.sleep(1000) it means UI thread will be blocking and UI not update First. If you want to wait and set Second you should use Handler. Try this

private void applicationTest()  {
    textTT.setText("First");
    new Handler().postDelayed({
           textTT.setText("Second");
    }, 1000)
}
Công Hải
  • 4,961
  • 3
  • 14
  • 20
0

Using thred.sleep is a very bad practice since you freeze the whole app! So you basically say: set text first but do nothing, then set second. So you see second. Instead you should use Handler. In that case you say: set first then create a parallel task that waits for 1sec before it executes. After 1 sec it sets second.

That is the code for this:

private void applicationTest()  {
    textTT.setText("First");
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
       @Override
       public void run() {
          textTT.setText("Second");
       } 
   }, 1000);
}
F.Mysir
  • 2,838
  • 28
  • 39
0

You should use Handler to achieve that:

private void applicationTest()  {
    textTT.setText("First");
    new Handler().postDelayed(new Runnable{
      @Override
      public void run() {
         textTT.setText("Second");
   } 
    },1000)
}
Pouya Heydari
  • 2,496
  • 26
  • 39