倒计时,物体位置在一定范围内

时间:2012-03-18 19:37:36

标签: android loops timer while-loop countdown

我正在尝试向用户显示一个从3到0倒计时的计时器。当用户在特定位置拖动对象时应该使该计时器可见,并且当用户拖动时应该停止(并重置)该计时器那个位置的对象..

目前,我正在使用Log.d,计时器的实际显示,稍后我会处理。

到目前为止,我有(非工作代码):

 public void setX(float x) {
        isCheckOut = false;              
    // if basket is further than slotmargin 
     if (x + width/2 > SlotManager.SlotmarginX) {
        // if basket is NOT in CheckOut area    
         if (this.Y < MainGamePanel.height - 80 - height/2){
            x = SlotManager.SlotmarginX - width/2;

        } else {
            // if basket IS in CheckOut area
            x = MainGamePanel.width - width/2;
            isCheckOut = true;
            GameManager.CheckOut();
        }
        }

     this.X = x;
 }

并且,在GameManager中:

public static void CheckOut() {

    Thread t = new Thread(new Runnable() {
      public void run() {
            while (basket.isCheckOut == true){

                for (int i=3;i>3;i--){
                    final Handler handler = new Handler(); 
                    Timer t = new Timer(); 
                    t.schedule(new TimerTask() { 
                            public void run() { 
                                    handler.post(new Runnable() { 
                                            public void run() { 
                                                Log.d("", "Countdown " + i);
                                            } 
                                    }); 
                            } 
                    }, 2000); 

                }

            }
      }
    });
    t.start();      
}

我觉得我到了某个地方,但无法绕过循环计时器组合。当isCheckOut == false时,计时器应该停止。现在,我想我开始计时器反复...并且我不能使用int“i”来显示当前的倒计时int,因为它不是最终的?

非常感谢帮助!

1 个答案:

答案 0 :(得分:1)

更好地使用这种方法:

final int delayMillis = 1000;

final boolean count = true;

final Handler handler = new Handler();

final Runnable runnable = new Runnable()
{

    @Override
    public void run()
    {

        // your code

        if (count) // stop timer when count is false
        {
            handler.postDelayed(runnable, delayMillis);
        }

    }
};

开始使用计时器:

handler.postDelayed(runnable, delayMillis);