我正在尝试制作一个按钮,当单击它时,它会更改其颜色图像并在方法 activeDelay() 中启动倒计时器,如下所示:
piscaAutoButton = (Button) rootView.findViewById(R.id.piscaAutoButton);
piscaAutoButton.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(final View view) {
if (sessionManager.getPisca()) {
sessionManager.setPisca(false);
trigger = false;
piscaAutoButton.setBackgroundResource(R.drawable.button_bg_round);
} else {
sessionManager.setPisca(true);
piscaAutoButton.setBackgroundResource(R.drawable.button_add_round);
trigger = true;
activeDelay(trigger);
}
这是我的 activeDelay 方法:
private boolean activeDelay(boolean trigger) {
while (trigger) { // LOOP WHILE BUTTON IS TRUE CLICKED
int timerDelay = manualControl.getDelayPisca(); //input for timer
//delay manual
new CountDownTimer(timerDelay * 1000, 1000) {
public void onFinish() {
System.out.println("sent");
try {
System.out.println("blink button " + manualControl.getBlinkButton());
if (!manualControl.getBlinkButton().isEmpty()) {
MenuActivity.mOut.write(manualControl.getBlinkButton().getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void onTick(long millisUntilFinished) {
}
}.start();
}
return trigger;
}
我的问题是我需要计数器在完成后继续运行,当用户再次单击按钮时停止(trigger = false)。我在编程时遇到问题,如果有人可以帮忙,我知道 activeDelay 内的返回会从方法中弹出,我们该如何解决这个问题,tks
最佳答案
我建议您不要使用 CountDownTimer(这会在某个特定时间段内运行),而应该使用 Handler(这会无限运行)。我正在向您发送处理程序代码。
private Handler handler = new Handler();
//call this when you want to start the timer .
handler.postDelayed(runnable, startTime);
Runnable runnable = new Runnable() {
@Override
public void run() {
// Do here , whatever you want to do(show updated time e.t.c.) .
handler.postDelayed(this, xyz); //xyz is time interval(in your case it is 1000)
}
};
//Stop handler when you want(In your case , when user click the button)
handler.removeCallbacks(runnable);
关于java - Android 通过点击按钮停止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44127570/