使用布尔值的两个功能的按钮?

时间:2017-12-16 05:18:13

标签: java android button boolean

我刚开始一个新的应用项目,但我遇到了问题。我想在android中有一个Button,一旦按下,再次按下时会切换到另一个函数,使用布尔值。如果您需要上下文,我会为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");

    }

2 个答案:

答案 0 :(得分:0)

尝试创建一个新的 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 } } }); 代码如下

json

答案 1 :(得分:0)

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

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