gpt4 book ai didi

java - android - 倒计时后打开 Activity

转载 作者:行者123 更新时间:2023-12-02 03:08:46 25 4
gpt4 key购买 nike

在我的新游戏中,你必须按下按钮才能获得积分。玩家必须在 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();
}
}

最佳答案

这是实现您想要的目标的简单而复杂的方法。

在全局级别定义一个 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();

}

关于java - android - 倒计时后打开 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41361144/

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