【问题标题】:button with two functions using Booleans? [duplicate]使用布尔值的具有两个功能的按钮? [复制]
【发布时间】:2017-12-16 05:18:13
【问题描述】:

我刚刚开始了一个新的应用项目,但遇到了问题。我想在android中有一个按钮,一旦按下,再次按下时会使用布尔值切换到不同的功能。如果您需要什么上下文,我正在为CountDownTimer 制作一个开始/停止按钮。我想知道这只是我脑海中浮现的一个简单概念,还是一个实际复杂的过程。谢谢!

注意:这不是在讨论长按按钮时的处理。这是关于在第一次按下按钮时处理按钮,以及在第二次按下按钮时处理。

这是我的代码:

TextView timerText;
CountDownTimer countDownTimer;
Button controlButton;
boolean timerisActive;

public void controlClick(View view) {

        countDownTimer = new CountDownTimer(timerTime + 100, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                Long minutes = millisUntilFinished / 1000 / 60;
                Long seconds = millisUntilFinished / 1000 - minutes * 60;
                String secondString = seconds.toString();
                String minuteString = minutes.toString();
                if (seconds <= 9) {
                    secondString = "0" + secondString;
                }
                timerText.setText(minuteString + ":" + secondString);
            }

            @Override
            public void onFinish() {
                timerText.setText("0:00");
            }

        }.start();
        if(timerisActive = true){
            countDownTimer.cancel();
            timerText.setText("0:00");
        }
        controlButton.setText("Stop");

    }

【问题讨论】:

  • 不,上面的问题是关于点击和长按的不同动作,而不是处理不同状态下的点击。
  • 谢谢安东尼。我编辑了澄清这一点的问题。希望这不会被标记。

标签: java android button boolean


【解决方案1】:

尝试这样创建一个新的boolean 变量,如下所示

 boolean isfirstTime = true;

根据该布尔值在第一次或第二次使用单击时进行检查

让你的button.setOnClickListener 像下面的代码

button.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
       if (isfirstTime) {
           // call here first time action
           isfirstTime=false;
       }else {
          // call here second time action
         // make isfirstTime = true; 
         // if you want to perform again first time action after second time use press the button
       }


     }
});

【讨论】:

    【解决方案2】:

    一种可能的方法是,您首先创建一个操作界面,例如:

    interface ButtonAction {
        void perform();
    }
    

    然后您创建一系列将连续执行的操作。使用大小为 2 的数组为您提供切换操作集,而任何更大的大小都将为您提供切换操作集的灵活性。

    private ButtonAction[] allButtonActions = ... // Create the concrete action implementations.
    

    并保留活动操作的索引:

    private int activeActionIndex = 0;
    

    然后在按钮点击事件处理程序中:

    allButtonActions[activeActionIndex].perform();
    
    // Perform next action at next click.
    activeActionIndex++;
    
    // Wrap to first action if reached last action already.
    if (activeActionIndex >= allButtonActions.length) {
        activeActionIndex = 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2012-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 2011-12-12
      • 2022-01-26
      • 1970-01-01
      相关资源
      最近更新 更多