Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add time to countdown timer?

I know there is a post like this but it does not answer the question clearly. I have a little game where you tap a head and it moves to a random position and you get +1 to score. Meanwhile there is a timer counting down from 60000 (60 seconds) and displaying below. How can I make it so whenever the head is tapped, it adds a second to the timer?

new CountDownTimer(timer, 1) {
    public void onTick(long millisUntilFinished) {
        textTimer.setText("Timer " + millisUntilFinished/1000);
    }
    public void onFinish() {
        Intent intent = new Intent(MainActivity.this, Gameover.class);
        startActivity(intent);
    }
}.start();

and in the onClickListner event I have:

timer=timer+1000;

It currently doesn't work as in there is no time added on the click.

Any help would be appreciated :)

like image 825
AtomicTim Avatar asked Dec 26 '22 01:12

AtomicTim


1 Answers

You can't change the time of a scheduled timer. The only way to achieve what you are trying to do is by cancelling the timer and setting up a new one.

public class CountdownActivity extends Activity implements OnTouchListener{
    CountDownTimer mCountDownTimer;
    long countdownPeriod;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_countdown);
       countdownPeriod = 30000;
       createCountDownTimer();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (mCountDownTimer != null)
                mCountDownTimer.cancel();
        createCountDownTimer();

        return true;
    }

    private void createCountDownTimer() {
        mCountDownTimer = new CountDownTimer(countdownPeriod + 1000, 1) {

            @Override
            public void onTick(long millisUntilFinished) {
                    textTimer.setText("Timer " + millisUntilFinished / 1000);
                countdownPeriod=millisUntilFinished;
            }

            @Override
            public void onFinish() {
                Intent intent = new Intent(MainActivity.this, Gameover.class);
                startActivity(intent);
            }
        };
    }
}
like image 141
G_J Avatar answered Jan 12 '23 06:01

G_J