gpt4 book ai didi

java - android - 多次运行计时器倒计时错误

转载 作者:行者123 更新时间:2023-12-01 09:03:38 26 4
gpt4 key购买 nike

在我的游戏中,当用户在 5 秒内从左向右扫过屏幕时,就会得分。如果他从右向左扫动或需要超过 5 秒,则游戏结束。在他获得刷新计时器的分数后,我试图取消倒计时。当用户扫错时我也尝试取消它。我遇到的问题是,当用户获得一分时,倒计时不会停止计数,并且当出现故障时,因此游戏应该结束,计时器在停止并打印 GameOver 之前倒计时上次运行的剩余时间。使用全局定时器有错吗?

  public class GameScreen extends Activity implements OnGestureListener {

private boolean animationRunning = false;
public int sco = 0;
float x1, x2;
float y1, y2;
public TextView text;
public TextView scorete;
private static final String FORMAT = "%02d:%02d";
CountDownTimer mCountDownTimer;


@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
text = (TextView) this.findViewById(R.id.textView3);
scorete = (TextView) findViewById(R.id.textView1);
scorete.setText(String.valueOf(sco));
load();

}

private void load() {
// TODO Auto-generated method stub

mCountDownTimer = new CountDownTimer(5000, 10) { // adjust the milli
// seconds here
public void onTick(long millisUntilFinished) {
text.setText(""
+ String.format(
"%02d:%03d",
TimeUnit.MILLISECONDS
.toSeconds(millisUntilFinished)
- TimeUnit.MINUTES
.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millisUntilFinished)),
TimeUnit.MILLISECONDS
.toMillis(millisUntilFinished)
- TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS
.toSeconds(millisUntilFinished))));

}

public void onFinish() {
text.setText("GameOver.");

}
};
mCountDownTimer.start();
}

@Override
public boolean onTouchEvent(MotionEvent touchevent) {

switch (touchevent.getAction()) {

case MotionEvent.ACTION_DOWN: {

x1 = touchevent.getX();
y1 = touchevent.getY();
break;
}
case MotionEvent.ACTION_UP: {

x2 = touchevent.getX();
y2 = touchevent.getY();

if (!animationRunning) {
// if left to right sweep event on screen
if (x1 < x2 && (x2 - x1) >= (y1 - y2) && (x2 - x1) >= (y2 - y1)) {

mCountDownTimer.cancel();
sco++;
scorete.setText(String.valueOf(sco));

load();
}

// if left to right sweep event on screen
else if (x1 > x2 && (x1 - x2) >= (y1 - y2) && (x1 - x2) >= (y2 - y1)) {

animationRunning = true;
mCountDownTimer.cancel();
text.setText("GameOver.");

}
}

}
}
}
}

最佳答案

重新启动计时器时,我建议调用start而不是重新实例化 CountDownTimer通过调用 load方法。

改变

mCountDownTimer.cancel();
sco++;
scorete.setText(String.valueOf(sco));
load();

mCountDownTimer.cancel();
sco++;
scorete.setText(String.valueOf(sco));
mCountDownTimer.start();

关于java - android - 多次运行计时器倒计时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41470919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com