I would like to know if it's possible to use handler().postdelayed twice?
I mean, I want to create a button, that when clicked it change the color and stay in this state 1 second, then, after 1 second another button change the color.
I've created the following code:
In the onclicklistener:
btn3.setBackgroundColor(Color.WHITE);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
checkAnswer();
waitAnswer();
btnRsp3.setBackgroundResource(R.drawable.selector);
}
}, 1000);
CheckAnswer:
public void CheckAnswer(){
btn1.setBackgroundColor(Color.GREEN);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
}
}, 500);
btn1.setBackgroundResource(R.drawable.selector);
}
I think the problem is on CheckAnswer because it seems it doesn't stop in this postDelayed and step to the waitAnswer.
Thanks
Annotation Android. Android. OS Handler. Post Delayed Method Android. OS Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses.
In android Handler is mainly used to update the main thread from background thread or other than main thread. There are two methods are in handler. Post () − it going to post message from background thread to main thread using looper.
sendmessage () − if you want to organize what you have sent to ui (message from background thread) or ui functions. you should use sendMessage (). This example demonstrate about how to handler in Progress Dialog. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
You're almost using postDelayed (Runnable, long) correctly, but just not quite. Let's take a look at your Runnable. final Runnable r = new Runnable () { public void run () { handler.postDelayed (this, 1000); gameOver (); } };
new Handler().postDelayed(new Runnable()
{
@Override
public void run()
{
//Your Work
}
}, 1000);
Why do you expect it to stop on postDelayed? postDelayed places your Runnable to the Handler Looper queue and returns. Since both handlers are created on the same looper, the second runnable is executed after the first one terminates (plus whatever left of the 500 ms delay)
UPDATE:
You need something like that
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
btn1.setBackgroundColor(Color.GREEN);
}
}, 1000);
handler.postDelayed(new Runnable() {
@Override
public void run() {
btn1.setBackgroundResource(R.drawable.selector);
}
}, 2000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With