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 T
Solution 1:
Use Handler
with postDelayed
, example:
finalHandlerhandler=newHandler();
handler.postDelayed(newRunnable() {
@Overridepublicvoidrun() {
Log.d("Log:", "Hello!");
handler.postDelayed(this, 1000);
}
}, 1000);
Solution 2:
You can use Handler:
for (inti=0; i < 10; i++) {
Handlerhandler=newHandler();
Runnabler=newRunnable() {
publicvoidrun() {
intrandom= r.nextInt(100) - 10;
Stringrand= Integer.toString(random);
textView3.setText(rand);
}
};
handler.postDelayed(r, 1000);
}
look at this question: How to run a Runnable thread in Android?
Solution 3:
I'm not very familiar with android app programming
But if you want a random number is printed to the text for every one second... how about using Timer instead of Delay?
I don't know how the code in Android works but the Logic should be like this:
Button Pressed:
Timer.Start(1000)
For every timer tick:
int numberVariable = random(1,10)
textVariable = numberVariable.toString()
Solution 4:
Add a handler with a timer, like this:
publicHandlerhandler=newHandler();
handler.postDelayed(newRunnable() {
@Overridepublicvoidrun() {
// Do something after 5s = 5000ms
}
}, 5000);
Solution 5:
You can use the Handler class to delay the loop for whatever amount of time you want. It goes like this.
Handlerhandler=newHandler();
handler.postDelayed(newRunnable() {
@Overridepublicvoidrun() {
//Your function goes here.
}
}, 5000); /your time in micro seconds.
Hope it helps.
Post a Comment for "How Can I Delay Onclick Action"