I'm solving an exercise for my university and there is this code in my pdf that my supposed to use to delay the change of the colour of the text on a button, i don't understand how it exactly works so please can someone explain it
HandlerThread handlerThread = new HandlerThread("showText");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
Runnable runnable = new Runnable() {
int i = 0;
@Override
public void run() {
i ;
handler.postDelayed(this, 1000);
if (i > 1)
button.setTextColor(getResources().getColor(android.R.color.transparent));
}
};
handler.post(runnable);
CodePudding user response:
This code is in obscure way causing that Runnable to be called with the delay of 1s (every second) because it reschedules itself each time. The int i
is guarding button.setTextColor
from executing the first the.
This code is however very messy, the way it should be done is as follows:
Runnable runnable = new Runnable() {
@Override
public void run() {
button.setTextColor(getResources().getColor(android.R.color.transparent));
}
};
handler.postDelayed(runnable, 1000);
or with lambda expression just as following:
handler.postDelayed(() -> button.setTextColor(getResources().getColor(android.R.color.transparent)), 1000);