取消自动倒数计时器

时间:2015-12-25 15:47:11

标签: android countdowntimer

我有一个CountDownTimer。当我给出答案时,我希望它停止。如果按下按钮(ant1或ant2),它将打开一个新的XML而不停止计时器。这是我的代码:

public class Vraag1 extends Activity {
    TextView text1;

    private static final String FORMAT = "%02d:%02d:%02d";

    int seconds , minutes;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.vraag1);

        text1=(TextView)findViewById(R.id.textView1);

        CountDownTimer countDownTimer = new CountDownTimer(30000, 1000) { 

            public void onTick(long millisUntilFinished) {

                text1.setText(""+String.format(FORMAT,
                        TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
                                TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
                                TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
            }

            public void onFinish() {
                Intent c = new Intent(Vraag1.this, MainActivity.class);
                startActivity(c);
            }
        }.start();

    }

    @Override
    public void onBackPressed() {

        Intent a = new Intent(Vraag1.this, MainActivity.class);
        startActivity(a);
    }

    public void onButtonClick(View v) {

        if (v.getId() == R.id.Ant1) {
            Intent i = new Intent(Vraag1.this, Vraag1Fout.class);
            startActivity(i);
        }
        if (v.getId() == R.id.Ant2) {
            Intent i = new Intent(Vraag1.this, Vraag1Fout.class);
            startActivity(i);
        }
        if (v.getId() == R.id.Ant3) {
            Intent i = new Intent(Vraag1.this, Vraag1Goed.class);
            startActivity(i);
        }
        if (v.getId() == R.id.Ant4) {
            Intent i = new Intent(Vraag1.this, Vraag1Fout.class);
            startActivity(i);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

  

我有一个CountDownTimer。当我给出答案时,我希望它停止

要停止它,当您按下按钮时,您必须在cancel();实例上调用CountDownTimer。如果你保持

CountDownTimer countDownTimer

作为类成员,并在onCreate中正确分配countDownTimer,然后您可以在调用cancel()时使用它来调用onClick。这将取消CountDownTimer