Bruno Morales
Bruno Morales

Reputation: 43

Android Radio Group multiple selection issue

I'm programatically creating a series of radio buttons in a radiogroup:

for (Soldier soldier:clickedSquad.getMembers()) {
                Integer I=0;
                soldier.setId(I);
                RadioButton radiobutton=new RadioButton(getContext());
                radiobutton.setText(soldier.toString());
                radiobutton.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                radiobutton.setId(soldier.getId());
                I++;
                soldierRgrp.addView(radiobutton);
            }

It creates the radiobuttons as I intend, but when I click several they all stay clicked like a checkbox, and I need only one to be clicked at a time like radiobuttons usually do.

Any idea why this is happening?

The radiogroup is in the XML and looks as follows:

    <RadioGroup
    android:layout_margin="10dp"
    android:id="@+id/reg_rgrp_soldiers"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</RadioGroup>

Upvotes: 3

Views: 3264

Answers (1)

Shaishav
Shaishav

Reputation: 5312

RadioButtons behave that way only if they same id. In your case they do! You are initialising your variable I=0 each time. Hence, each soldier is given the same id. Soldiers don't particularly like that! Change you code to:

      int i=0;
      for (Soldier soldier:clickedSquad.getMembers()) {
            soldier.setId(i++);
            RadioButton radiobutton=new RadioButton(getContext());
            radiobutton.setText(soldier.toString());
            radiobutton.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            radiobutton.setId(soldier.getId());
            soldierRgrp.addView(radiobutton);
        } 

Upvotes: 8

Related Questions