Handler handler = new Handler();
if (v.getId() == R.id.play){
handler.postDelayed(new Runnable() {
public void run() {
play.setBackgroundResource(R.drawable.ilk);
}
}, 2000);
play.setText("Play");
}
I want to set background first and then after 2 seconds later, code will continue next line which is play.setText("Play");
and goes like that. Instead of this, first text appears. 2 seconds later background changes.
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue . Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler it is bound to a Looper .
Handler is better than TimerTask . The Java TimerTask and the Android Handler both allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handler over TimerTask in Android (see here, here, here, here, here, and here).
You can use Handler to add a Runnable object or messages to the Looper to execute the code on the thread associated with the Looper. Android associates each Handler instance with a single thread and that thread's message queue. Whenever you create a new Handler instance, it is tied up to a single Looper .
Handler.postDelayed
returns immediately. And next line is executed.
After indicated milliseconds, the Runnable
will be executed.
So your code should be like this:
void doFirstWork() {
Handler handler = new Handler();
if (v.getId() == R.id.play){
handler.postDelayed(new Runnable() {
public void run() {
play.setText("Play");
doNextWork();
}
}, 2000);
play.setBackgroundResource(R.drawable.ilk);
}
}
void doNextWork() {
...
}
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