2013-05-06 131 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 ==