如何使按钮取消CountDownTimer

编程入门 行业动态 更新时间:2024-10-09 01:22:12
本文介绍了如何使按钮取消CountDownTimer-Android应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个带有以下代码的倒数计时器,如何使按钮(i.d button2)停止(或取消)计时器.但也要这样做,如果时间用完了,可以将它们用于Scores.class.

I have a Count down timer with the following code, how can I make a button (i.d button2) stop (or cancel) the timer. but also make it so if the time runs out they are intent'ed to 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(); }

推荐答案

不要只使用"new CountDownTimer"(不实例化CountDownTimer对象),否则您基本上将无法再次引用它.

Don't just use "new CountDownTimer" (without instantiating a CountDownTimer object) or else you basically won't have a way to reference it again.

因此,改为创建一个实际的CountDownTimer对象,例如

So instead, make an actual CountDownTimer object, e.g.

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或您要启动"计时器的任何地方.

Notice there I did not include the ".start()". That is because you will call it later e.g. in onCreate, or wherever you want to "start" your timer.

因此,在onCreate(例如)中,写:

So, in onCreate (for example), write:

myCountDownTimerObject.start();

然后,在onClick中为您的按钮键入以下内容:

Then, inside your onClick for your button, type this:

myCountDownTimerObject.cancel();

我希望这会有所帮助!

编辑

EDIT

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(); }}); } }

更多推荐

如何使按钮取消CountDownTimer

本文发布于:2023-11-28 01:06:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640361.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   CountDownTimer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!