2013-05-06 119 views
0

我有一个onCheckedChanged,它告诉我是否有RadioButtonRadioGroup被推送。字符串没有取值

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(); 
       } 
      } 
     }); 

当我使用的是现在outcommented第一Toast,它告诉我,TMP是“Männlich”或“Weiblich”。当我使用第二个Toast t1,我告诉我geschlecht是空的。 geschlecht的声明是在我的班级的顶部,因为我也需要它在我的onCreate类。

为什么geschlecht没有采用tmp的价值?

+0

检查条件与“equalsIgnoreCase”。 – pudaykiran 2013-05-06 08:53:24

回答

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) 
+0

好的,当然。我多么愚蠢。谢谢!在可能的时候会接受你的答案 – user896692 2013-05-06 08:55:25

1

你是不是你的代码比较字符串的内容,而是对象,使用equalsequalsIgnoreCase,像这样:

if ("Männlich".equalsIgnoreCase(tmp)) { 
    geschlecht = "männlich"; 
} 
if ("Weiblich".equalsIgnoreCase(tmp)) { 
    geschlecht = "weiblich"; 
} 
1

使用tmp.compareTo ("Mannlich")tmp ==