Android点击按钮停止循环

时间:2017-05-23 06:44:51

标签: java android loops methods while-loop

我正在尝试创建一个按钮,当它单击时,它会更改其彩色图像并在方法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

1 个答案:

答案 0 :(得分:1)

我建议你不要使用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);