0

私は今、最初にプレーヤーがボタンの色を見て、5 秒後にすべてのボタンの色が消え、ユーザーが勝つために同じ色のものを選ばなければならないゲームを作っています。

5 秒の待機時間は、 を使用しhandlerて実行を待機し、同時に で 5 秒のカウントダウンを表示してCountDownTimer、プレイヤーが残り時間を知るようにしました。

ユーザーが現在のゲームをあきらめた場合、再起動ボタンをクリックして別のゲームを開始できます。

すべてが正常に実行され、プレーヤーが再起動ボタンをクリックすると、プログラムはすべてのボタンの色を消す前に 5 秒間待機する必要があることも認識しています。

質問:

5秒カウントダウンの表示についてです。ユーザーが 1 ゲームを開始すると、カウントダウンの開始がカウントされます。ユーザーが再起動ボタンをもう一度押すと (たとえば 3 秒後)、元のカウントダウンは終了せず、両方のカウントダウンが同時に表示されます。プレイヤーがリスタートボタンを押した場合、前のカウントダウンを終了する方法を教えてください。

コード:

protected void onCreate(Bundle savedInstanceState) 
{
        ...other actions

    restart.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) 
        {
            handler1.removeCallbacks(txtClearRun);
            SetNewQ();
        }
    });

    SetNewQ();      

} // end onCreate

private void SetNewQ() 
{       
    MyCount5sec counter5sec = new MyCount5sec(5000,1000);
    counter5sec.start();
    ...other actions below
}   

   public class MyCount5sec extends CountDownTimer
   {
       public MyCount5sec(long millisInFuture, long countDownInterval) {super(millisInFuture, countDownInterval);}
       @Override
       public void onFinish() 
       {
           ButtonRemainTime= (Button) findViewById(R.id.button_remaintime); 
           ButtonRemainTime.setText("Add oil!!");
           // game then start by blanking out all the colors
       }
       @Override
       public void onTick(long millisUntilFinished) 
       {
           ButtonRemainTime= (Button) findViewById(R.id.button_remaintime); 
           ButtonRemainTime.setText("" + millisUntilFinished/1000);
       }
4

1 に答える 1

1

あなたの質問が何を求めているかはわかっていますが、個人的には次の方法でセットアップを調整します。CountDownTimerクラスが他にあまり実装していない場合は、実際にクラスを宣言してfieldインスタンス化することができます。

protected void onCreate(Bundle savedInstanceState) 
{
        ...other actions

    restart.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) 
        {
            handler1.removeCallbacks(txtClearRun);
            MyCount5sec.start(); // ----------changed this line
        }
    });

    MyCount5sec.start(); // ---------- changed this line

} // end onCreate

CountDownTimer MyCount5sec = new CountDownTimer(5000,1000) {

    @Override
    public void onTick(long millisUntilFinished) {
           ButtonRemainTime= (Button) findViewById(R.id.button_remaintime); 
           ButtonRemainTime.setText("" + millisUntilFinished/1000);         
    }

    @Override
    public void onFinish() {
           ButtonRemainTime= (Button) findViewById(R.id.button_remaintime); 
           ButtonRemainTime.setText("Add oil!!");
           // game then start by blanking out all the colors            
    }
}; 

このようにする利点は、常に同じオブジェクトを参照していることです。onClickそれぞれに新しいタイマーを作成してから、他のタイマーをキャンセルする必要はありません。実際、この同じタイマー オブジェクトで早い段階でタイマーcancelを呼び出すと、タイマーが再起動されるだけなので、その必要はまったくありません。start

于 2012-12-22T13:53:06.123 に答える