我的计时器会在达到一定数量时停止。相反,我希望它停止点击按钮。我怎么做? 这就是我目前的代码:
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时,我希望它在按钮点击时停止。
答案 0 :(得分: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();
}
});
答案 1 :(得分:0)
使用CountDownTimer。单击该按钮时,只需停止计时器。
但是你要继续创建一个按钮,在按钮上设置一个OnClickListener,然后调用timer.cancel()或者在你的侦听器的onClick()方法中停止它。