SRam
SRam

Reputation: 2828

Add radio button dynamically in an Android app

I need to add radio button dynamically. A radio button may be 3, 4, 5 or 6 and it would be added horizontally and one row contains maximum 3 radio button.

If there are more than 3 then it would come below of above row of radio button as in grid view. My code for radio button are below but it display all radio button in a single row, means it's hiding the radiobutton.

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
 android:orientation="vertical" >

   <TextView
 android:id="@+id/TextView01"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Choose Your Favorite Actress" >
  </TextView>

 <RadioGroup
android:id="@+id/RadioGroup01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
 </RadioGroup>
 <Button
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" >
 </Button>
</LinearLayout>

And Java class is:

  @Override
  public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       DisplayRadioButton();
  }


  public void DisplayRadioButton() {
       for(int i=0;i<10;i++) {
           RadioGroup radiogroup = (RadioGroup)findViewById(R.id.RadioGroup01);
           RadioButton rdbtn = new RadioButton(this);
           rdbtn.setId(i);
           rdbtn.setText(text[i]);
           radiogroup.addView(rdbtn);
  }

}

Upvotes: 2

Views: 9993

Answers (1)

M.A.Murali
M.A.Murali

Reputation: 10148

please try in the following way:

1)in your xml remove the RadioGroup. create it by dynamically

RadioGroup radiogroup[];
RadioButton rdbtn[];
LinearLayout linear[]; 

radiogroup = new RadioGroup[9/3];
rdbtn = new RadioButton[9];
linear = new LinearLayout[9/3];

......
int count = 0; // integer flag

for(int i=0;i<9;i++){

  if the value of i is equal to 3 multiple then increase count by 1
         // sett linear[count]'s orientation is horizontal.

         root_layout.addView(linear[count]);
         radiogroup[count] = new RadioGroup(this);
         linear[count].addView(radiogroup[count]);  // add radio group to linear layout

       add radio button to radio group.

          rdbtn[i] = new RadioButton(this);
          rdbtn[i].addView(radiogroup[count]);


}

i hope you get solved. be aware of array index out of bound exception.

your xml may look like:

<LinearLayout
           android:id= rootlayout
           ..... // the child linearlayout
                     .. . radio group
                        ... radio button
 </LinearLayout>   

Upvotes: 3

Related Questions