Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inflating RadioGroup in Android-multiple radioButtons check at a time

I made a RadioGroup with a variable number of radioButtons. The problem is that many radiobuttons can be checked, it is not a single RadioButton checked in a RadioGroup (as I know) Where is my mistake? Here is my code :

View view = inflater.inflate(R.layout.questionnaire_check_question, null);
RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
    for (int k = 0; k < answerValues.size(); k++) {
         View radioButtonView = inflater.inflate(R.layout.check_radio_button, null);
         RadioButton radioButton = (RadioButton) radioButtonView
                            .findViewById(R.id.radio_button);
         radioButton.setText(answerValues.get(k));
         radioGroup.addView(radioButtonView);
    }
questionBody.addView(view);

questionnaire_check_question.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp"
    android:background="#A4A7A6" >

    <RadioGroup
        android:id="@+id/radioGroup"
        android:scrollbars="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
    </RadioGroup>

</LinearLayout>

check_radio_button.xml

<?xml version="1.0" encoding="utf-8"?>
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/radio_button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:layout_marginLeft="5dp"
    android:button="@drawable/checkbox"
 >

</RadioButton>

drawable/checkbox.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:drawable="@drawable/icon_checkbox_on" android:state_checked="true"/>
    <item android:drawable="@drawable/icon_checkbox_off" android:state_checked="false"/>

</selector>

The radioGroup has a strange functionality..if I check the first RadioGroup, and then the second one, the first on become unchecked...after this, if I want to select again the first one, I can't do this..it doesn't check anymore. Can anyone help me ? Any idea is welcome! Thanks in advance.

like image 528
Gabrielle Avatar asked Jul 17 '13 07:07

Gabrielle


1 Answers

I found the solution: the problem was that all buttons have the same ID. So I set a unique id for each radioButton.

like image 87
Gabrielle Avatar answered Nov 13 '22 03:11

Gabrielle