java - 从多个单选按钮获取文本
问题描述
我想从多个选中的单选按钮中获取文本,并在一个编辑文本中检索它......但不知道最好的方法是什么。什么是更好的?将结果保存在字符串或列表中?
无论如何,结果应该出现在一个单一的编辑文本中,每个文本之间都有空格。例如……狗、猫、老鼠。
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);
}
解决方案
如果您想要事件驱动的代码,那么使用列表可能更容易管理,具体取决于您拥有多少按钮以及如何操作。但是在您的确切示例中,一个字符串就绰绰有余了。正如评论中所建议的,您可以简单地附加文本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;
...
推荐阅读
- scala - 如何在 Scala 中过滤掉字符串向量中的一次出现?
- java - 我可以在不手动下载二进制文件的情况下运行 PhantomJS 吗?
- python-3.x - 将Django中的对象列表序列化为嵌套的json
- c++ - 向量是否也在 C++ 中初始化原始类型?
- clojure - Luminus H2留言簿应用程序中没有合适的驱动程序
- python - 在 Notebook Python 中禁用 tesseract 字典
- javascript - 对象没有被传递到本地存储 - React JS
- php - 在灵活的列中显示数据,而不是在 php 中的行
- reactjs - 反应排序列表 - 点击事件触发不正确
- time-complexity - 生成括号时空复杂度