按下按钮时状态不变

时间:2014-11-18 09:50:28

标签: java android button onclick boolean

每当我按下按钮时,它应该更改文本,并且还会更改布尔值,但这不起作用。有帮助吗? Thnks

在onCreate之前:

public boolean status = false;

按钮点击:

case R.id.saveButton:   

if (status != true) {
    currentStatus.setText("Current status: In need of help!");
    status = true;
}
if (status != false) {
    currentStatus.setText("Current status: Fine.");
    status = false;
}
break;

5 个答案:

答案 0 :(得分:3)

if(status){
       currentStatus.setText("Current status: Fine.");
       status = false;
}else {                             
       currentStatus.setText("Current status: In need of help!");
       status = true
}

或使用三元运算符:

currentStatus.setText(status ? "Current status: Fine." : "Current status: In need of help!");
status = !status;//toggle boolean value

答案 1 :(得分:1)

如果条件工作布尔状态所以当检查条件是否使用布尔变量时不需要使用==或!=运算符简单把布尔变量放在小括号中:

if(status){
 // this code executed when status is value is - true 
}else{
 // this code executed when status is value is - false
}

答案 2 :(得分:0)

试试这个: 实际上,您在代码中两次更改了状态。

    case R.id.saveButton:   

            if(status == false){
                currentStatus.setText("Current status: In need of help!");

                status = true;

            }
            else if(status == true){
                currentStatus.setText("Current status: Fine.");
                status = false;

            }
        break;

答案 3 :(得分:0)

修改后的代码:您必须在代码中的第一个else语句后使用if

        boolean status = false;

        System.out.println("status : "+status); // False

         if(status != true){
             status = true;
         }else if(status != false){   // add else here to resolve issue
             status = false;
         }

         System.out.println("status : "+status); // True

答案 4 :(得分:0)

我认为您没有在按钮上调用setOnClickListener。

实施 View.OnClickListener 界面

Button saveButton = (Button)findViewById(R.id.saveButton);
saveButton.setOnClickListener(this);

并在

@Override
public void onClick(View v) {

  if(status){
     currentStatus.setText("Current status: Fine.");
     status = false;
  }else {                             
     currentStatus.setText("Current status: In need of help!");
     status = true
  }
}
相关问题