Search code examples
javaandroiddelaywaitseconds

How to set a delay between setting texts in Android


How do I set multiple delays between bt.setText("№")?

    public void buttonOnClick (View button) {
    final Button bt = findViewById(R.id.button);
    bt.setText("3");
    //wait 1 second
    bt.setText("2");
    //wait 1 second
    bt.setText("1");
    //wait 1 second
    bt.setText("Click!");

Solution

  • Since you can't call Thread.sleep on the UI thread (only the final result would be displayed) you should do this on anhother Thread, such:

    on constructor:

    private Handler handler;
    public void onCreate(Bundle x) {
         //super and get bt
         final Button bt = findViewById(R.id.button);
         handler = new Handler() {
               public void handleMessage(Message msg) {
                    if(msg.what == 0)
                         bt.setText("Click!");
                    else
                         bt.setText(String.toString(msg.what));
               }
         }
    }
    
    public void buttonOnClick (View button) {
       final Button bt = findViewById(R.id.button);
       bt.setText("3");
       //wait 1 second
       handler.sendEmptyMessageDelayed(2, 1000);
       //wait 2 second
       handler.sendEmptyMessageDelayed(1, 2000);
       //wait 3 second
       handler.sendEmptyMessageDelayed(0, 1000);
       bt.setText("Click!");
    }
    

    Note that I did used msg.what that is a identifier for such, but you could just create a message with an obj parameter that you could use later.