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类实现的其他内容不多,您实际上可以声明类 afield并一举实例化它。

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

The benefit of doing it like this is that you'd always be referring to the same object. you wouldn't have to make a new timer on each onClick and then manage cancelling the other one. In fact, you wouldn't even have to cancel at all because calling start on the timer early on this same timer object will just restart it.

于 2012-12-22T13:53:06.123 回答