2

问题是:如何在倒计时期间从 CountDownTimer 添加或删除时间?

例如:用户做了好事:+5sec,用户做错事:-5sec。

有人可以帮我一些代码吗?

4

3 回答 3

6

也许是这样的

abstract class MyTimer {

    public MyTimer(long deadline, long interval)
    {
        mDeadline = deadline;
        mInterval = interval; 

        mTimer = new MyCountDownTimer(mDeadline, mInterval);

    }

    public synchronized void start() {

       mTimer.start();

    }

    public abstract void onTick(long time);
    public abstract void onFinish();

    public synchronized void userDidRight() 
    {
        mTimer.cancel();
        mTimer = new MyCountDownTimer(mDeadline, mInterval += 5000);
        mTimer.start();
    }

    public synchronized void userDidWrong() 
    {
        mTimer.cancel();
        mTimer = new MyCountDownTimer(mDeadline, mInterfval -= 5000);
        mTimer.start();
    }


    private class MyCountDownTimer extends CountDownTimer() {

        private abstract void onFinish() {
            MyTimer.this.onFinish();
        }

        private abstract void onTick(long time) {
            MyTimer.this.onTick(time);
        }
    }

    private MyCountDownTimer mTimer;
}
于 2012-07-24T12:21:49.863 回答
1

每次用户更改时,您都可以重新启动计时器:

class Timer {
    private long remainingTime;
    private CoundDownTimer timer;

    public void addTime(long addedTimeInMillis) {
      createNewTimer(remainingTime + addedTimeInMills);
    }

    public void createNewTimer(long timeInMillis) {
       if(timer != null) {
         timer.cancel();
       }
       timer = new CountDownTimer(timeInMillis, 1000) {

       @Override
       public void onTick(final long millisUntilFinished) {
           remainingTime = millisUntilFinished;
       }

       @Override
       public void onFinish() {
           // do something here
       }
       }.start();

    }
}
于 2012-07-24T12:23:06.633 回答
1
private class startTimer extends CountDownTimer
{

    public startTimer(long millisInFuture, long countDownInterval)
    {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onTick(long millisUntilFinished) {
        currenttime=millisUntilFinished;
        textview.setText("" + currenttime / 1000);
    }

    @Override
    public void onFinish() {
        textview.setText("done");
    }
}

上面的类是CountDownTimer的一个简单派生类

CountDownTimer timer = new CountDownTimer(30000,1000);
timer.start();
long currentTime;

例如上面的计时器从 30 秒开始,每秒减一。要动态增加或减少计时器,您可以取消旧计时器并使用新时间进行初始化,如下所示

 timer.cancel();
 timer = new CountDownTimer(currentTime+5000,1000);// +5000 to increase by 5 secs
 timer.start();

您可以将 timer,currentTime 变量设为全局变量,然后您可以在不同位置使用代码的两个不同部分。

于 2015-01-27T10:57:55.757 回答