问题
This question is similar to this one but this question is little bit different.
I am creating 15 RadioGroups and 4 radio buttons inside each group using for loop.
for(int i=0; i<15; i++) {
RadioGroup radioGroup = new RadioGroup(getActivity());
radioGroup.setOrientation(RadioGroup.HORIZONTAL);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
radioGroup.setLayoutParams(lp);
radioGroup.setId(i+1);
for(int j=0; j<4; j++) {
RadioButton radioButton = new RadioButton(getActivity());
radioGroup.addView(radioButton);
}
radioGroup.setOnCheckedChangeListener(radioListener);
}
And this is radio listener code:
final RadioGroup.OnCheckedChangeListener radioListener = new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
RadioButton radio = (RadioButton) rootView.findViewById(checkedId);
String selectedValue = radio.getText().toString();
}
};
The above code is responsible for the exception. According to Android developers, checkedId
is
the unique identifier of the newly checked radio button
The problem with this code is that it works sometimes and doesn't works other times. There are a total of 15 radiogroups so if I select radiobuttons from 2nd to 15th group, it will show no error and everything will execute perfectly but when I select the 1st radio button of the very first radio group, it throws the exception - cannot cast android.widget.radiogroup
to android.widget.radiobutton
来源:https://stackoverflow.com/questions/38216284/android-cannot-cast-android-widget-radiogroup-to-android-widget-radiobutton