3

我目前正在创建一个具有不同选项的 android 应用程序。一种选择是有一个按钮,默认显示“激活”。当应用程序正在运行时,单击它会将其更改为“禁用”,然后再次单击将其更改为“激活”。我相信我所要做的就是使用字符串变量 .getText 然后在 if 语句中使用这个变量,但它似乎对我的任何条件都没有反应......

        final Button button = (Button) findViewById(R.id.bSensor);


    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click

            String buttonText = button.getText().toString();    
            if (buttonText == "@string/Disable") {
                button.setText(R.string.Enable);
            }
            else if (buttonText == "@string/Enable"){
                button.setText(R.string.Disable);
            }

        }
    });

感谢帮助

菲齐克

4

2 回答 2

2

在 Java 中比较字符串时不应使用 == 运算符。 来源

您应该使用字符串的 .equals() 方法,或者您可以保留一个全局布尔状态标志来确定设置了哪个值。这样您就不需要每次需要确定它是活动的还是禁用的时都进行字符串比较。

于 2012-11-08T19:46:54.893 回答
1

用于.equals比较字符串。您不需要@String/前缀,因为这不是按钮显示的一部分。

final Button button = (Button) findViewById(R.id.bSensor);

button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // Perform action on click

        String buttonText = button.getText().toString(); 

        if (buttonText.equals(getResources().getText(R.string.Disable)) {
            button.setText(R.string.Enable);
        }
        else if (buttonText.equals(getResources().getText(R.string.Enable)){
            button.setText(R.string.Disable);
      }

    }
});
于 2012-11-08T19:51:34.093 回答