如何使按钮取消CountDownTimer - Android应用程序

时间:2014-04-01 20:54:45

标签: android button timer

我有一个带有以下代码的倒计时器,如何使按钮(i.d button2)停止(或取消)计时器。但是如果时间用完了它们也是如此,它们意图被Scores.class。

计时器代码:

LevelOne context;
@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    setContentView(R.layout.activity_level_one);

    context = this;

    new CountDownTimer(1500, 1500) {
        public void onTick(long millisUntilFinished) {

        }

        public void onFinish() {

            Intent intent = new Intent(context, Scores.class);
            startActivity(intent);
        }
    }.start();

}

1 个答案:

答案 0 :(得分:1)

不要只使用“new CountDownTimer”(不实例化CountDownTimer对象),否则你基本上无法再次引用它。

相反,请创建一个实际的CountDownTimer对象,例如

CountDownTimer myCountDownTimerObject = new CountDownTimer(1500, 1500)
{
    public void onTick(long millisUntilFinished) {

    }

    public void onFinish() {

        Intent intent = new Intent(context, Scores.class);
        startActivity(intent);
    }
};

请注意,我没有包含“.start()”。那是因为你稍后会打电话,例如在onCreate中,或者您想要“启动”计时器的任何地方。

所以,在onCreate(例如)中,写一下:

myCountDownTimerObject.start();

然后,在onClick for your button中输入:

myCountDownTimerObject.cancel();

我希望这有帮助!

修改

public class MyActivity extends Activity {


    Button myButton;

    CountDownTimer timer = new CountDownTimer(30000, 1000)
    {

        @Override
        public void onFinish() {
            Intent intent = new Intent("com.example.intentForYourActivity");
            startActivity(intent);
        }

        @Override
        public void onTick(long arg0) {
            //do something
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //ass soon as this activity is created, I start my timer.
        timer.start();

        myButton = (Button) findViewById(R.id.cancel);

        myButton.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                timer.cancel();
            }});
    }
}