Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delay onClick action

I am trying to do something in java app (android) and I need something to delay/wait for an amount of seconds for a loop. How can I do delay android function? I have tried to use Thread.sleep(), TimeUnit.sleep, but it is only going to do irresponsible program for some seconds. I want to do some onClick actionlistener which updating for some seconds. e.g: if I clicked to button -> Text is changed to random(int) and it's should be done per second.

random ... waiting for a second ... random ... waiting for a second ... random ... and so many times

for (int i = 0; i < 10; i++) {
    int random = r.nextInt(100) - 10;
    String rand = Integer.toString(random);
    textView3.setText(rand);
    TimeUnit.SECONDS.sleep(1);
}
like image 933
phen0menon Avatar asked Jan 28 '26 03:01

phen0menon


1 Answers

Use Handler with postDelayed, example:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    Log.d("Log:", "Hello!");
    handler.postDelayed(this, 1000);
  }
}, 1000);
like image 168
Damian Kozlak Avatar answered Jan 29 '26 15:01

Damian Kozlak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!