我有一个onCheckedChanged
,告诉我RadioButton
中的RadioGroup
是否被推送。
RadioGroup rGroup = (RadioGroup)findViewById(R.id.rdgroup);
// This will get the radiobutton in the radiogroup that is checked
RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(rGroup.getCheckedRadioButtonId());
rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup rGroup, int checkedId)
{
// This will get the radiobutton that has changed in its check state
RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(checkedId);
// This puts the value (true/false) into the variable
boolean isChecked = checkedRadioButton.isChecked();
// If the radiobutton that has changed in check state is now checked...
if (isChecked)
{
String tmp = checkedRadioButton.getText().toString();
//Toast t = Toast.makeText(NeuesKind.this, checkedRadioButton.getText(), Toast.LENGTH_SHORT);
//
// t.show();
if(tmp == "Männlich"){
geschlecht = "männlich";
}
if(tmp == "Weiblich"){
geschlecht = "weiblich";
}
Toast t1 = Toast.makeText(NeuesKind.this, geschlecht, Toast.LENGTH_SHORT);
t1.show();
// Toast t = Toast.makeText(NeuesKind.this, checkedRadioButton.getText(), Toast.LENGTH_SHORT);
// t.show();
}
}
});
当我使用现在已经过时的第一个Toast
时,它告诉我tmp是“Männlich”或“Weiblich”。当我使用第二个Toast t1
时,我告诉我geschlecht
为空。
geschlecht的声明是我班上最重要的,因为我在onCreate
课程中也需要它。
为什么geschlecht没有取tmp的值?
答案 0 :(得分:3)
在Java中,执行==
意味着它将比较两个对象的引用。您需要通过调用字符串equals
方法来实际比较对象中的文本,如下所示:
if (tmp.equals("Männlich")) {
geschlecht = "männlich";
}
if (tmp.equals("Weiblich")) {
geschlecht = "weiblich";
}
但是,这样做也会容易得多:
geschlecht = tmp.toLowerCase(); // toLowerCase will make all the characters lowercase (as you've done in your if block)
答案 1 :(得分:1)
您没有将字符串内容与您的代码进行比较,而是将对象与equals
或equalsIgnoreCase
进行比较,如下所示:
if ("Männlich".equalsIgnoreCase(tmp)) {
geschlecht = "männlich";
}
if ("Weiblich".equalsIgnoreCase(tmp)) {
geschlecht = "weiblich";
}
答案 2 :(得分:1)
使用tmp.compareTo ( "Mannlich" )
而不是tmp ==