计时器不会在android中停止

BIB*_*RAL 7 android timer

我在android中创建了一个应用程序并使用了这样的计时器..

try {
    CountDownTimer  start1 = new CountDownTimer(20000, 1000) {

        public void onTick(long millisUntilFinished) {
                TextView timeShow = (TextView)findViewById(R.id.showTime);
        timeShow.setText(" "+" 00:" +millisUntilFinished / 1000);
            }
Run Code Online (Sandbox Code Playgroud)

但我的问题是我不知道如何停止计时器.任何的想法?

我已经尝试过:

quitApplication.setOnClickListener(new OnClickListener() {
    public void onClick(View v) { 
        start1.cancel(); 
        Intent i = new Intent(v.getContext(), startGame.class);
        startActivity(i);
        // TODO Auto-generated method stub 
    } 
}); 
Run Code Online (Sandbox Code Playgroud)

Ton*_*han 10

start1.cancel() 是调用取消计时器的正确方法.

你没有提供任何关于你得到的错误或为什么它不适合你的细节,但我假设你的程序没有编译,因为你的变量start1是一个局部变量.它可能是你的try块所在的任何方法都是本地的.这意味着你的OnClickListener构造不知道它是什么start1.

要解决此问题,只需将其声明 start1为类变量(在所有方法之外但在类中):

public class someClass {

CountDownTimer start1;
// blah some code
public void someMethod {
   try {
      start1 = new CountDownTimer() { //etc
Run Code Online (Sandbox Code Playgroud)

这样做将允许其他方法识别和交互 start1