![](/img/trans.png)
[英]How can I get id/text of all selected radiobuttons in a recyclerview?
[英]Get text from multiples radiobuttons
我想从多个选中的单选按钮中获取文本,并在一个编辑文本中检索它......但不知道如何做到这一点。 什么是更好的? 将结果保存在字符串或列表中?
无论如何,结果应该出现在一个编辑文本中,每个文本之间都有空格。 例如……狗、猫、老鼠。
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;
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.