【问题标题】:Android stop loop by click buttonAndroid通过点击按钮停止循环
【发布时间】:2017-05-23 06:44:51
【问题描述】:

我正在尝试制作一个按钮,当它被点击时,它会更改其颜色图像并在方法 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;
    }

我的问题是我需要计数器在完成后继续运行,当用户再次单击按钮时停止(触发器 = false)。我在编程时遇到问题,如果有人可以提供帮助,我知道 activeDelay 中的返回会从方法中弹出,我们该如何解决,tks

【问题讨论】:

    标签: java android loops methods while-loop


    【解决方案1】:

    我建议你不要使用 CountDownTimer(this run for some specific time period) ,而不是使用 Handler(this run infinite) 。我正在向您发送处理程序代码。

      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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      相关资源
      最近更新 更多