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 时停止。

4

2 回答 2

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();
        }
});
于 2012-07-30T17:59:07.057 回答
0

使用倒数计时器。单击按钮时,只需停止计时器。

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

于 2012-07-30T17:57:31.027 回答