在我的新游戏中,您必须按一个按钮才能获得积分。玩家必须在5秒内按下按钮 - 如果花费更多时间,GameOverScreen将被打开。否则倒计时应重新开始。我试图将gameover();
方法放在倒计时的finish()
方法中,但似乎有可能始终启动finish方法并且不会取消。我怎样才能停止倒计时呢?
public class GameScreen extends Activity {
public int score = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Button count = (Button) findViewById(R.id.button1);
text = (TextView) this.findViewById(R.id.textView3);
tvscore = (TextView) findViewById(R.id.score);
timer();
}
public void gameover() {
Intent intent = new Intent(this, GameOverScreen.class);
startActivity(intent);
}
public void onClick (View view) {
score++;
tvscore.setText(String.valueOf(score));
timer();
}
public void timer(){
new CountDownTimer(5000, 10) {
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))
));
if(animationRunning) {
cancel();
}
}
public void onFinish() {
text.setText("Too slow.");
gameover();
}
}.start();
}
}
答案 0 :(得分:2)
这是实现您想要的简单而复杂的方式。
在全局级别定义CountDownTimer的对象
CountDownTimer mCountDownTimer ;
在onCreateView中:
mCountDownTimer = new CountDownTimer(5000, 10) {
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));
}
@Override
public void onFinish() {
text.setText("Too slow.");
gameover();
}
};
mCountDownTimer.start();
在onClick()
public void onClick (View view)
{
mCountDownTimer.cancel();
score++;
tvscore.setText(String.valueOf(score));
mCountDownTimer.start();
}
答案 1 :(得分:0)
像这样更新您的计时器代码:
private boolean isTimerCanceled = false;
public void timer(){
new CountDownTimer(5000, 10) {
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))
));
if(animationRunning)
{
isTimerCanceled = true;
cancel();
} else{
isTimerCanceled = false;
}
}
public void onFinish()
{
if (!isTimerCanceled){
text.setText("Too slow.");
gameover();
}
}
}.start();
}