2017-07-30 2 views
0

Android Studioで小さなゲームを作っています。基本的に、ユーザーはボタンを押すトリガーに設定された時間が経過するか、ゲームが終了します。私のCountDownTimerオブジェクトは、私のボタンクリックハンドラとは異なる機能の中にあります。ボタンクリックハンドラからcancel()を使用してcountDownTimerをキャンセルするにはどうすればよいですか?ここでCountDownTimerにアクセスしてJavaでキャンセルするにはどうすればよいですか?

は私のコードです:

public countDownTimer timeLimit; 

public void generate() { 
    final ProgressBar timer = (ProgressBar)findViewById(R.id.timer);` 
     int timeoutSeconds = 5000; 
     timer.setMax(timeoutSeconds); 
     timeLimit = new CountDownTimer(timeoutSeconds, 100) { 

      public void onTick(long millisUntilFinished) { 
       int timeUntilFinished = (int) millisUntilFinished; 
       timer.setProgress(timeUntilFinished); 
      } 

      public void onFinish() { 
       gameOver(); 
      } 
     }; 
     timeLimit.start(); 
} 

public void buttonClicked(View v) { 
    timeLimit.cancel(); 
} 

私もこれを行うには、任意の代替の方法を聞くことが幸せになると思います。

+0

ローカル変数の代わりにフィールド変数として宣言します。 –

+0

timeLimitタイマーを、通常はデータメンバーと呼ばれるクラスレベルの変数として作成します。 –

+0

これを行う方法に関するサンプルコードまたはドキュメントはありますか? – NoobProgrammer

答えて

0
The code below works perfectly for me. 

public class MainActivity extends AppCompatActivity implements View.OnClickListener { 

private ProgressBar progressBar; 
private CountDownTimer countDownTimer; 
private Button stopTimerButton; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    progressBar = (ProgressBar)findViewById(R.id.progressBar); 
    stopTimerButton = (Button)findViewById(R.id.button); 
    stopTimerButton.setOnClickListener(this); 
    int timeoutSeconds = 5000; 
    progressBar.setMax(timeoutSeconds); 
    countDownTimer = new CountDownTimer(timeoutSeconds,100) { 
     @Override 
     public void onTick(long millisUntilFinished) { 
      int timeUntilFinished = (int) millisUntilFinished; 
      progressBar.setProgress(timeUntilFinished); 
     } 

     @Override 
     public void onFinish() { 

     } 
    }; 
    countDownTimer.start(); 

} 

@Override 
public void onClick(View view) { 
    if(view == stopTimerButton){ 
     countDownTimer.cancel(); 
    } 
} 
}