2012-07-24 31 views

回答

5

也許這樣的事情

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

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

可以使計時器,currentTime的變量作爲全球那麼你可以使用的兩個不同的部分代碼在不同的位置。

相關問題