按钮单击时等待计时器不重启

时间:2015-01-14 21:31:46

标签: android countdowntimer

在我的应用程序中,我想要一个按钮来启动倒数计时器,例如:

@Override
public void onClick(View v) {
    switch (v.getId()) {

        case R.id.Next:

            // Define CountDown Timer Attributes//
            waitTimer1 = new CountDownTimer(45191, 1000) {


                @Override
                public void onTick(long millisUntilFinished) {
                    long timeLeft = millisUntilFinished / 1000;
                    Timer.setText("" + String.format("%d min, %d sec",
                            TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                            TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));

                }

                @Override
                public void onFinish() {

                }

            }.start();


            // Repeat Words//
            if (word.getText().toString().equals("Big Foot")) {

                stringListCounter = 0;

            }
            // Change To Next Word//
            stringListCounter++;
            word.setText(stringIdList[stringListCounter]);

           break;
        }

    }
}

一旦计时器第一次启动,我希望能够再次点击该按钮,而不会重新启动计时器。

例如(仅用于解释的假例子),如

 if(timer has started) {

     doNothingToTimer;
}

1 个答案:

答案 0 :(得分:1)

我认为问题在于每次点击按钮时都会重新初始化时间。

@Override
public void onClick(View v) {
switch (v.getId()) {

    case R.id.Next:
        if (waitTimer1 == null){
        // Define CountDown Timer Attributes//
        waitTimer1 = new CountDownTimer(45191, 1000) {


            @Override
            public void onTick(long millisUntilFinished) {
                long timeLeft = millisUntilFinished / 1000;
                Timer.setText("" + String.format("%d min, %d sec",
                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));

            }

            @Override
            public void onFinish() {

            }

        }.start();
        }//end-if
        else{
            //
            //do other button stuff
        }


        // Repeat Words//
        if (word.getText().toString().equals("Big Foot")) {

            stringListCounter = 0;

        }
        // Change To Next Word//
        stringListCounter++;
        word.setText(stringIdList[stringListCounter]);

       break;
    }

}

}