Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

android - 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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...