我有一个问题 当我的活动开始时,第一个倒计时正在运行 我想要做的是停止第一次倒计时,当我按下按钮,然后第二次倒计时运行 第二部分有效,但我不知道如何阻止第一次倒计时 任何Button都不会调用它,但它会在Activity启动时启动。
我希望你明白我在说什么 抱歉我的英语不好。
这是我的代码:
Button finnish;
TextView letter;
TextView textViewState, textVievCity, textViewRiver, textViewPlant, textViewAnimal, textViewName;
EditText editTextState, editTextCity, editTextRiver, editTextPlant, editTextAnimal, editTextName;
TextView textViewAnswer1, textViewAnswer2, textViewAnswer3, textViewAnswer4, textViewAnswer5, textViewAnswer6;
TextView timer, timer1;
public int counter = 120;
public int finalCounter = 10;
public int counterStop = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Button finnish = (Button) findViewById(R.id.buttonFinnished);
finnish.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final TextView timer1 = (TextView) findViewById(R.id.textViewFinalCOunter);
new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timer1.setText(String.valueOf(finalCounter));
finalCounter--;
}
@Override
public void onFinish() {
timer1.setText("koniec rundy");
}
}.start();
}
});
TextView letter = (TextView) findViewById(R.id.textViewLetter);
final String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "ł", "m", "n", "o", "p", "r", "s", "t", "u", "w", "z"};
int random = (int) (Math.random() * 23);
letter.setText(letters[random]);
final TextView timer = (TextView) findViewById(R.id.textViewTimer);
new CountDownTimer(120000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
if (timer1 != null) {
timer.setText(String.valueOf(counterStop));
} else {
timer.setText(String.valueOf(counter));
counter--;
}
}
@Override
public void onFinish() {
timer.setText("koniec rundy");
}
}.start();
}
}
答案 0 :(得分:0)
如果要停止引用,则需要存储对CountDownTimer
的引用,例如
private CountDownTimer firstCountDown;
firstCountDown = new CountDownTimer(120000, 1000){...};
然后,您可以通过按下ClickListener
按钮来取消第一次倒计时,CountDownTimer#cancel()
就像这样
@Override
public void onClick(View v) {
firstCountDown.cancel()
...
}