Android - cannot cast android.widget.RadioGroup to android.widget.RadioButton

故事扮演 提交于 2020-01-07 00:34:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!