2014-02-14 54 views
0

在我開始我已經看過很多線程包括:如何給正在運行的倒數計時器添加時間?

How to add time to countdown timer? Android game countdown timer

但我就是不能讓我的計時器我要求的工作方式。我想讓計時器從30開始倒計時,並按下時間和圖像(在這種情況下命名爲imageview1),計時器會爲計時器增加3秒鐘時間,以給予它更多的時間。我知道你不能本質上增加了時間,而它的運行,你需要先取消,然後開始一個新的計時器,我到目前爲止的代碼是:

public void onClick(View v) { 
    // TODO Auto-generated method stub 
    //GlobalClass global = new GlobalClass(); 
    Random rand = new Random(); 

    CountDownTimer thetimer = new myTimer(millisInFuture, 1000); 

    switch(v.getId()) { 

    case R.id.buttonstart: 
     btnstart.setVisibility(View.INVISIBLE);  
     thetimer.start(); 
     break; 

    case R.id.imageView1:  
     if (thetimer != null){ 
      thetimer.cancel(); 
      thetimer = new myTimer(countdownPeriod + 3000, 1000).start(); 

     } 

     break; 

與許多其他情況下引用的則:

public class myTimer extends CountDownTimer { 

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

     @Override 
     public void onTick(long millisUntilFinished) {   
       timedisplay.setText("Time Left: " + millisUntilFinished/1000); 
       countdownPeriod=millisUntilFinished; 

     } 

     @Override 
     public void onFinish() { 
      timedisplay.setText("Timer Finished"); 
      started = false; 
      btnstart.setVisibility(View.VISIBLE); 
     } 
    } 

我認爲問題在於它沒有取消原定時器,所以顯示定時器的標籤會做一些瘋狂的事情,比如在不同的數字上下跳動,因爲會出現超過1個類的時間。即使我已經包含了行thetimer.cancel();如果我只是讓它運行到0

任何幫助將是巨大的

回答

1

你不應該在onClick創建計時器作爲本地定時器工作正常。相反,將其創建爲全局並在其他地方啓動它(也許在onCreate)。

與您現有的代碼會發生什麼情況是,每當onClick被稱爲一個新的計時器創建,然後取消新的計時器 - 這對任何先前創建的定時器(S)沒有影響。

嘗試是這樣的:

public class MyActivity extends Activity { 

    CountDownTimer thetimer; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     thetimer = new myTimer(millisInFuture, 1000); 
    } 

    public void onClick(View v) { 
     Random rand = new Random(); 
     switch(v.getId()) { 
     case R.id.buttonstart: 
      btnstart.setVisibility(View.INVISIBLE);  
      thetimer.start(); 
      break; 

     case R.id.imageView1:  
      if (thetimer != null) { 
       thetimer.cancel(); 
       thetimer = new myTimer(countdownPeriod + 3000, 1000).start(); 
      } 
      break; 
     } 
    }  
} 

您仍然需要跟蹤的全球時間的地方 - 即使用countDonwPeriod當圖像被觸摸到重新創建定時器實例 - 這大概應該是在取消之前從定時器提取。

+0

嗨,謝謝你的回覆。我改變它來聲明onclick方法外的倒數計時器(小學生錯誤),但當點擊imageview時它仍然無法停止計時器....例如timer.cancel();任何其他想法? – Xeo

+0

我覺得它有一些與我公共類JavaMenu擴展活動實現onclicklistener。我刪除了實現onclicklistener,並拿出了案例的聲明,取而代之的是與每個人imgviews等現在工作的Onclick聽衆...不是100%爲什麼它不開心我的原始設置方式工作....但它現在是大聲笑...一個週末確實爲大腦的奇蹟。感謝您的幫助 – Xeo