按下按钮后增加速度的倒数计时器

时间:2015-07-05 07:48:43

标签: android timer countdowntimer

我正在尝试创建一个倒数计时器,按下按钮后我会使用计数器来调整进度条。

现在我按下按钮后调整速度(增加),但它不是从头开始。例如,当我启动程序时,计时器从头开始逐渐减少,这很好。但是,当我按下按钮时,计数器不会从头开始,如下所示: enter image description here enter image description here enter image description here

我希望在按下每个按钮后让它运行得更快,而不是减少长度。

这是我的代码:

 mTrueBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //is the user right? if pressing True button
            if(isMathProblemTrue == 1){
                //user is correct
                Toast.makeText(MainActivity.this,"Correct!",Toast.LENGTH_SHORT).show();
                generateMathProblem();
                timer_length *= 0.8;
                timer_interval *= 0.8;
                Log.d(TAG,"time length:"+timer_length);
                Log.d(TAG,"time interval:"+timer_interval);
                mCountDownTimer.cancel();
                createNStartTimer();
                //restartTimer();
            }else{
                //user is incorrect
                transferUserToStartScreen();
                //reset the timer
                mCountDownTimer.cancel(); // cancel
            }
        }
    });
private void createNStartTimer() {
    mCountDownTimer = new CountDownTimer(timer_length,timer_interval) {
        @Override
        public void onTick(long millisUntilFinished) {
            Log.d(TAG,"Mil until finish:"+millisUntilFinished);
            int progress = (int) (millisUntilFinished/100);
            mProgressBar.setProgress(progress);
        }
        @Override
        public void onFinish() {
            mProgressBar.setProgress(0);
            transferUserToStartScreen();
        }
    }.start();
}

1 个答案:

答案 0 :(得分:1)

在函数之外创建2个全局常量

int totalMillisUntilFinished = 0;
bool firstTime = true;

我们在暂时调用totalMillisUntilFinished时初始化onTick,因此请更新您的onTick函数:

private void createNStartTimer() {
    firstTime = true;
    mCountDownTimer = new CountDownTimer(timer_length,timer_interval) {
        @Override
        public void onTick(long millisUntilFinished) {
            if(firstTime){totalMillisUntilFinished = millisUntilFinished; firstTime = false;}
            Log.d(TAG,"Mil until finish:"+millisUntilFinished);
            int progress = (int) (millisUntilFinished*100/totalMillisUntilFinished);
            mProgressBar.setProgress(progress);
        }

就个人而言,我使用的是HandlersRunnable,我肯定会建议您这样做。