首页 > 解决方案 > 从多个单选按钮获取文本

问题描述

我想从多个选中的单选按钮中获取文本,并在一个编辑文本中检索它......但不知道最好的方法是什么。什么是更好的?将结果保存在字符串或列表中?

无论如何,结果应该出现在一个单一的编辑文本中,每个文本之间都有空格。例如……狗、猫、老鼠。

if (radioButton.isChecked()){
                String obs2 = radioButton.getText().toString();
                texto.setText(obs2);
            }
            if (radioButton3.isChecked()){
                String obs2 = radioButton3.getText().toString();
                texto.setText(obs2);
            }
            if (radioButton4.isChecked()){
                String obs2 = radioButton4.getText().toString();
                texto.setText(obs2);
            }
            if (radioButton5.isChecked()){
                String obs2 = radioButton5.getText().toString();
                texto.setText(obs2);
            }
            if (radioButton6.isChecked()){
                String obs2 = radioButton6.getText().toString();
                texto.setText(obs2);
            }
            if (radioButton7.isChecked()){
                String obs2 = radioButton7.getText().toString();
                texto.setText(obs2);
            }
            if (radioButton8.isChecked()){
                String obs2 = radioButton8.getText().toString();
                texto.setText(obs2);
            }

            editText1 = here should get the text of each radio button checked

新尝试:

if (radioButton.isChecked()){
                obs2 = checkNullAndAppend(obs2, (String) radioButton.getText());
            } else if (radioButton3.isChecked()){
                obs2 = checkNullAndAppend(obs2, (String) radioButton3.getText());
            } else if (radioButton4.isChecked()){
                obs2 = checkNullAndAppend(obs2, (String) radioButton4.getText());
            } else {
                texto.setText(obs2);
            }

标签: javaandroid-studio

解决方案


如果您想要事件驱动的代码,那么使用列表可能更容易管理,具体取决于您拥有多少按钮以及如何操作。但是在您的确切示例中,一个字符串就绰绰有余了。正如评论中所建议的,您可以简单地附加文本texto.setText(texto.getText() + "," + obs2);

如果你想避免空值问题或减少重复代码,那么有很多不同的方法可以做到这一点,但一种是创建一个简单的方法:

public static String checkNullAndAppend(String existing, String toAppend){
    //Check null
    if (existing == null || existing.equals(""))
        return toAppend;
    //Otherwise add a comma and space
    else
        return existing + ", " + toAppend;
}

然后,您可以简单地在if语句中调用该方法:

if (radioButton.isChecked()){
    texto = checkNullAndAppend(texto, radioButton3.getText());
}
if (radioButton3.isChecked()){
    texto = checkNullAndAppend(texto, radioButton3.getText());
}
...

editText1 = texto;
...

推荐阅读