Mr. Pivirotto
Mr. Pivirotto

Reputation: 281

How to make timer stop on click

My timer will stop when it reaches a certain number. Instead, I want it to stop on a button click. How do I do that? This is what my code looks like currently:

final TextView t1 = (TextView) findViewById(R.id.yourpay);

final Timer t =new Timer();
t.schedule(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                    public void run() {
                        money = (PPS+Reserve);
                        Reserve = (money);
                        t1.setText("$" + money); //Place your text data here
                        counter++;

                        //Place your stopping condition over here. Its important to have a stopping condition or it will go in an infinite loop. 
                        if(counter == HPDPS)
                            t.cancel(); 
                    }
            }); 
        }
    }, 1000, 1000);

If possible I would like it to stop on button click AND when counter reaches HPDPS.

Upvotes: 1

Views: 3607

Answers (2)

Mxyk
Mxyk

Reputation: 10698

Put in your button's onClickListener():

if (t != null)
    t.cancel();

and remove the stopping condition from the timer.


Code Example (updated):

final TextView t1 = (TextView) findViewById(R.id.yourpay);

final Timer t =new Timer();
t.schedule(new TimerTask() {

    @Override
    public void run() {
        runOnUiThread(new Runnable() {

            public void run() {
                money = (PPS+Reserve);
                Reserve = (money);
                t1.setText("$" + money); //Place your text data here

                // Removed the stopping condition/counter

            }
        }); 
    }
}, 1000, 1000); // Do you really want to wait 1 second before executing the timer's code?  If not, change the 1st "1000" to a "0"


final Button b = (Button) findViewById(R.id.my_button_id); // Replace with your button's id
b.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        if (t != null)
            t.cancel();
        }
});

Upvotes: 2

Code Droid
Code Droid

Reputation: 10472

Use a CountDownTimer. When the button is clicked just stop the timer.

But for what you have just go ahead and create a button, set an OnClickListener on the button and then call timer.cancel() or whatever stops it inside on the onClick() method of your listener.

Upvotes: 0

Related Questions