gpt4 book ai didi

java - 安卓工作室 : Reset CountDownTimer

转载 作者:行者123 更新时间:2023-11-29 04:33:00 26 4
gpt4 key购买 nike

我有一个从 10 开始倒计时的计时器,当它达到零时,它会使数组中的随机 ImageView 变为可见。我只想让这个计时器在每次达到零时自行重置。我怎样才能做到这一点?

当前尝试:

public class rear_gunner extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rear_gunner);
View view2 = findViewById(R.id.item_frame);
final ImageView enemy1 = (ImageView) findViewById(R.id.enemy1);
ImageView enemy2 = (ImageView) findViewById(R.id.enemy2);
ImageView enemy3 = (ImageView) findViewById(R.id.enemy3);
ImageView enemy4 = (ImageView) findViewById(R.id.enemy4);
//sets screen orientation on created
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

view2.bringToFront();
final ImageView[] enemies = new ImageView[4];
enemies[0] = enemy1;
enemies[1] = enemy2;
enemies[2] = enemy3;
enemies[3] = enemy4;


Random rand = new Random();
int n = rand.nextInt(20) + 1;

CountDownTimer countDownTimer = new CountDownTimer(10000, 1000) {
@Override
public void onFinish() {
Random rand = new Random();
int n = rand.nextInt(3) + 1;
enemies[n].setVisibility(View.VISIBLE);
}

@Override
public void onTick(long millisUntilFinished) {

}

};

countDownTimer.start();
}


}

如有任何改进此处代码的帮助或建议,我们将不胜感激。

最佳答案

在 OnCreate() 之外创建对象 CountDownTimer,然后在 onFinish() 内完成随机后再次创建对象 .start()

CountDownTimer countDownTimer;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


countDownTimer = new CountDownTimer(2000, 1000) {
@Override
public void onFinish() {
//what you want to do after CountDownTimer is done
countDownTimer.start(); //start again
}

@Override
public void onTick(long millisUntilFinished) {

}

};

countDownTimer.start();
}

关于java - 安卓工作室 : Reset CountDownTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43023649/

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