如何使按钮取消CountDownTimer-Android应用 [英] How to make a button cancel a CountDownTimer - Android app
问题描述
我有一个带有以下代码的倒数计时器,如何使按钮(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-Android应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!