我为我的项目制作了一个倒计时器,它将运行2分钟(即120秒)1000是间隔时间(1000ms = 1s)然后我设置一个检查器,一个120的整数(全局声明),它将被减少每次计时器滴答一次.整数将显示在textVIEw倒计时.然后将在整数到达计时器的onFinish时显示一条消息.该消息将通过将声明的整数减去120来为我花费多少时间.
这里的问题是计时器在达到1之前停止,因为它不会被最后一次打勾扣除.最难的部分是有时它会在剩余时间内以4或甚至5停止.任何人可以帮我这个吗?提前致谢!
这是我的进一步理解的代码:
//declared a timerint timer = 120;//starts the timergameTimer = new gameTimer(120000,1000); gameTimer.start();private class gameTimer extends CountDownTimer{public gameTimer(long startTime,long interval){ super(startTime,interval);}public voID onTick(long millisUntilFinished){ //on tick deduct timer by 1 timer -= 1; TextVIEw timer1 = (TextVIEw)findVIEwByID(R.ID.textVIEw1); timer1.setText(""+timer);}public voID onFinish(){ //PERFORM END ACTION UPON FINISHING THE GAME endtime = 120 - timer; TextVIEw endtime1 = (TextVIEw)findVIEwByID(R.ID.textVIEw2); 1.setText(""+endtime);}}解决方法 第一个*:这是扩展* CountDownTimer的类:
public class GameTimer extends CountDownTimer{private YourActivity context;private int timer = 120;private int endtime;private TextVIEw timer1,endTime1;public gameTimer(YourActivity context,long startTime,long interval){ // passing the context of your activity this.context = context; //get the textVIEw to display results timer1 = (TextVIEw)this.context.findVIEwByID(R.ID.textVIEw1); endTime1 = (TextVIEw)this.context.findVIEwByID(R.ID.textVIEw2); super(startTime,interval);}public voID onTick(long millisUntilFinished){ //on tick deduct timer by 1 timer -= 1; //overrIDe the method runOnUIThread context.runOnUiThread(new Runnable(){ @overrIDe public voID run(){ timer1.setText(""+timer); } }); }public voID onFinish(){ //PERFORM END ACTION UPON FINISHING THE GAME endtime = 120 - timer; //overrIDe the method runOnUIThread context.runOnUiThread(new Runnable(){ @overrIDe public voID run(){ endTime1.setText(""+endtime); } });}}
第二:在你的活动中(在方法onCreate()上,实现你的GameTimer并启动它:
//instanciate the GameTimer and pass the context to itGameTimer gameTimer = new GameTimer(this,120000,1000); gameTimer.start();总结
以上是内存溢出为你收集整理的Android:Timer onTick问题全部内容,希望文章能够帮你解决Android:Timer onTick问题所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)