I have a animated loader in my application right now.
public void startLoader() {
Runnable task = new Runnable() {
@Override
public void run() {
lock = true;
loader.setVisibility(View.VISIBLE);
}
};
runOnUiThread(task);
}
public void stopLoader() {
Runnable task = new Runnable() {
@Override
public void run() {
lock = false;
loader.setVisibility(View.GONE);
}
};
runOnUiThread(task);
}
Now I want it to work like this:
stopLoader should have an delayed execution of like 1000ms, so it dissapears 1 second after stopLoader is called. but if the startLoader is called within that 1000ms the stopLoader timer would be cancelled.
What is the best way to implement this?
You should use Handler instead of runOnUiThread.
With handler you can cancel any delayed task using handler.removeCallbacks(runnable).
Handler mHandler = new Handler();
Runnable startTask = new Runnable() {
@Override
public void run() {
lock = true;
loader.setVisibility(View.VISIBLE);
}
};
Runnable stopTask = new Runnable() {
@Override
public void run() {
lock = false;
loader.setVisibility(View.GONE);
}
};
public void startLoader() {
mHandler.removeCallbacks(stopTask);
mHandler.post(startTask);
}
public void stopLoader() {
mHandler.postDelayed(stopTask, 1000);
}
Read more here
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