简体   繁体   中英

I need someone to explain for me this java code

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM