2016-08-20 33 views
1

我有一個測驗類型的應用程序,並且在每個問題上我都有一個讓用戶標記問題的選項。RadioGroup CheckedChangeListener錯誤索引

當我首先打開對話框時,一切正常,但如果我再次打開對話框導致索引增量。

例如,如果我按在指數5,結果指數是5,然後如果我再次打開對話框,按指數5再次結果是10

Dialog alert = new Dialog(this); 
    alert.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); 
    alert.setContentView(R.layout.dialog_layout); 

    RadioGroup mRadioGroup = (RadioGroup) alert.findViewById(R.id.dialog_radioGroup); 
    final String[] options = { 
      ((RadioButton)mRadioGroup.getChildAt(0)).getText().toString(), 
      ((RadioButton)mRadioGroup.getChildAt(1)).getText().toString(), 
      ((RadioButton)mRadioGroup.getChildAt(2)).getText().toString(), 
      ((RadioButton)mRadioGroup.getChildAt(3)).getText().toString(), 
      ((RadioButton)mRadioGroup.getChildAt(4)).getText().toString(), 
    }; 

    mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(RadioGroup radioGroup, int i) { 
      sendToServer = options[i]; 
     } 
    }); 
    alert.show(); 

它工作第一次,但如果我再試一次,我總會得到一個ArrayIndexOutOfBoundsException

回答

2

我想你混淆在RadioGroup.OnCheckedChangeListener 的PARAMS它想onCheckedChanged(RadioGroup group, int checkedId),你在你的代碼混淆checkedId爲指標i以上。

您可以檢查checkedId像下面

mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
      @Override 
      public void onCheckedChanged(RadioGroup group, int checkedId) { 
       for (int i = 0; i < group.getChildCount(); i++) { 
        if (group.getChildAt(i).getId() == checkedId) { 
         sendToServer = options[i]; 
         break; 
        } 
       } 
      } 
     }); 
+0

感謝我今天學到了新的東西:),我認爲我是指數,而不是ID非常感謝 –

+0

:)歡迎您,謝謝爲了投票 –

0

我能解決我的問題,這是不漂亮,但它的作品,我仍然不明白爲什麼該指數
自動遞增的聽衆

當用戶點擊發送,我運行這個檢查

if(((RadioButton) mRadioGroup.getChildAt(0)).isChecked()){ 
    index = 0; 
}else if(((RadioButton) mRadioGroup.getChildAt(1)).isChecked()){ 
    index = 1; 
}else if(((RadioButton) mRadioGroup.getChildAt(2)).isChecked()){ 
    index = 2; 
}else if(((RadioButton) mRadioGroup.getChildAt(3)).isChecked()){ 
    index = 3; 
} 
0

您的錯誤是OnCheckedChange方法傳遞視圖的id,而不是索引。您必須更改代碼以使用SparseIntArray而不是數組,並將每個值設置爲其id,而不是index。否則,您可以使用indexOfChild函數。