Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to restart a handler postdelay process if interupted during delay countdown

I have a problem that i can't work out. I have a button that when clicked changes the text view. It then activates a postdelayed process that returns the textview to its original text after 2 seconds.

If i press the button once, and then again within this 2 second interval the postdelay will continue to count down from the first press and not restart itself from the second press. This results in the original text being shown when i want the changed text to be.

Each time the button is pressed it creates a delay from that instance. I want it to cancel the previous postdelay and start a new one. This is my code so far but its not finished because i can't work out how to finish it (so it does not work).

p1AddL.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            counter1 ++;
            count1 ++;
            Handler h = new Handler();
            if ('PREVIOUS_DELAY_HAS_STARTED') {
                h.removeCallbacks(clickButton);
                h.postDelayed(clickButton, 2000);
            } else {
                h.postDelayed(clickButton, 2000);
            }
            if (count1 > 0) {
                lifepointsP1.setText("+" + count1);
                lifepointsP1.setTextColor(Color.argb(220, 0, 188, 0));
            }
        }
    });

Runnable clickButton = new Runnable() {
    @Override
    public void run() {
        count1 = 0;
        lifepointsP1.setTextColor(Color.WHITE);
        lifepointsP1.setText(counter1);
    }
};

the PREVIOUS_DELAY_HAS_STARTED text needs to be some sort of checking method and i'm pretty sure i need something between the h.removeCallbacks and h.postDelayed commands under that text.

If their is a simpler way/better way to write this method to make it work please let me know. I have tried so many ways and i feel i am very close here.

like image 991
RhysBailey21 Avatar asked Mar 19 '23 18:03

RhysBailey21


1 Answers

removeCallbacks won't do anything if clickButton isn't registered on h. So you can simply replace

if ('PREVIOUS_DELAY_HAS_STARTED') {
    h.removeCallbacks(clickButton);
    h.postDelayed(clickButton, 2000);
} else {
    h.postDelayed(clickButton, 2000);
}

with

h.removeCallbacks(clickButton);
h.postDelayed(clickButton, 2000);
like image 153
0101100101 Avatar answered Apr 06 '23 13:04

0101100101