正Piyush Gupta所提到的,您应该在您的容器中调用该
setTimer()方法。
onResume``QuestionActivity
来自Android开发者文档:
(onResume is) called for your activity to start interacting with the user.This is a good place to begin animations, open exclusive-access devices (suchas the camera), etc.
在你的代码也应该使
counterTimer你在使用
setTimer()一个 类成员 ,而不是一个局部变量;
如果不这样做,则在
setTimer()呼叫完成后它将超出范围,并且您对其的访问将丢失。
因此,您需要将以下内容添加到
QuestionActivity:
public class QuestionActivity extends Activity implements OnClickListener{ // NEW: add counterTimer as a member private CountDownTimer counterTimer; // NEW: implement onResume @Override public void onResume() { setTimer(); super.onResume(); } // CHANGE: setTimer should be changed as follows public void setTimer() { long finishTime = 5; // NOTE: use the member, instead of a local counterTimer = new CountDownTimer(finishTime * 1000, 1000) { public void onFinish() { //pre to execute when time finished } public void onTick(long millisUntilFinished) { int seconds = (int) (millisUntilFinished / 1000); int minutes = seconds / 60; seconds = seconds % 60; if (seconds < 10) { txtTimer.setText("" + minutes + ":0" + seconds); } else { txtTimer.setText("" + minutes + ":" + seconds); } } }; counterTimer.start(); }}这上面的例子使用你的代码,因为它是现在,但我会建议你在创建定时器
onCreate一切,这是目前在SetTimer的(),除了使用类成员来存储它(即
counterTimer.start();调用。然后,只需用
counterTimer.start();的
onResume。也许添加一个
counterTimer.cancel()呼叫,
onPause以便当活动失去焦点时计时器结束。



