2014-10-07 76 views
0

如何在每個按鈕點擊重新啓動計時器?這裏給出了定時器設置重新啓動或刷新一個定時器,當按鈕被點擊在android

new CountDownTimer(3000, 1000) { 

     public void onTick(long millisUntilFinished) { 
      //getSelectedAlphabet.setText(selectedIndex.getText()); 
     } 

     public void onFinish() { 
      //mTextField.setText("done!"); 
      getSelectedAlphabet.setVisibility(View.INVISIBLE); 

      Log.d("Counter", "Finished...."); 

     } 
     }.start(); 

回答

1

試試這個

CountDownTimer cdt; 
cdt = new CountDownTimer(3000, 1000) { 

     public void onTick(long millisUntilFinished) { 
      //getSelectedAlphabet.setText(selectedIndex.getText()); 
     } 

     public void onFinish() { 
      //mTextField.setText("done!"); 
      getSelectedAlphabet.setVisibility(View.INVISIBLE); 

      Log.d("Counter", "Finished...."); 

     } 
     }.start(); 

// to restart 
cdt.cancel(); // to cancel 
cdt.start(); //to start 
0
final CounterClass timer = new CounterClass(180000,1000); 

button.setOnclickListener(new OnClickListener() { 
       @Override 
       public void onClick(View view) { 
         timer.start(); 
       } 
     }; 

CounterClass-

public class CounterClass extends CountDownTimer { 
    public CounterClass(long millisInFuture, long countDownInterval) { 
     super(millisInFuture, countDownInterval); 
    } 

    @Override 
    public void onFinish() { 
     System.out.println("finished"); 
    } 


    @Override 
    public void onTick(long millisUntilFinished) { 
     long millis = millisUntilFinished; 
     String hms = String.format(
       "%02d:%02d:%02d", 
       TimeUnit.MILLISECONDS.toHours(millis), 
       TimeUnit.MILLISECONDS.toMinutes(millis) 
         - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS 
           .toHours(millis)), 
       TimeUnit.MILLISECONDS.toSeconds(millis) 
         - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS 
           .toMinutes(millis))); 
     System.out.println(hms); 

    } 
} 
1
final CountDownTimer remainingTimeCounter = new CountDownTimer(3000, 1000) { 
public void onTick(long millisUntilFinished) { 
     } 

     public void onFinish() { 
      Log.d("Counter", "Finished...."); 
     } 
    }.start(); 
findViewById(R.id.button1).setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     remainingTimeCounter.cancel(); 
     remainingTimeCounter.start(); 
     } 
    }); 
一個示例代碼
相關問題