2012-07-30 46 views
1

当我的计时器达到一定数量时,它会停止。相反,我希望它停止点击按钮。我怎么做? 这是我的代码看起来像现在:如何让定时器停止点击

final TextView t1 = (TextView) findViewById(R.id.yourpay); 

final Timer t =new Timer(); 
t.schedule(new TimerTask() { 

     @Override 
     public void run() { 
      runOnUiThread(new Runnable() { 

        public void run() { 
         money = (PPS+Reserve); 
         Reserve = (money); 
         t1.setText("$" + money); //Place your text data here 
         counter++; 

         //Place your stopping condition over here. Its important to have a stopping condition or it will go in an infinite loop. 
         if(counter == HPDPS) 
          t.cancel(); 
        } 
      }); 
     } 
    }, 1000, 1000); 

如果可能的话,我想它停止按钮点击,当计数器达到HPDPS。

回答

2

把你的按钮的onClickListener()

if (t != null) 
    t.cancel(); 

并从计时器停止条件。


代码示例(更新):

final TextView t1 = (TextView) findViewById(R.id.yourpay); 

final Timer t =new Timer(); 
t.schedule(new TimerTask() { 

    @Override 
    public void run() { 
     runOnUiThread(new Runnable() { 

      public void run() { 
       money = (PPS+Reserve); 
       Reserve = (money); 
       t1.setText("$" + money); //Place your text data here 

       // Removed the stopping condition/counter 

      } 
     }); 
    } 
}, 1000, 1000); // Do you really want to wait 1 second before executing the timer's code? If not, change the 1st "1000" to a "0" 


final Button b = (Button) findViewById(R.id.my_button_id); // Replace with your button's id 
b.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     if (t != null) 
      t.cancel(); 
     } 
}); 
+0

你能告诉我一个例子,我可以建立过的?就像我说的那样,真的很新,所以我真的不知道如何格式化onClickListener – Hockeyman271 2012-07-30 18:00:48

+0

有一个更新的代码示例。试试那个。 – Mxyk 2012-07-30 18:09:41

+0

非常感谢所有的帮助! @override出现了一些错误,所以我不得不删除它?我不知道为什么 – Hockeyman271 2012-07-30 19:27:43

0

使用CountDownTimer。点击按钮时,停止计时器。

但是对于你刚刚开始创建的按钮,在按钮上设置一个OnClickListener,然后调用timer.cancel(),或者在侦听器的onClick()方法中停止它。