Haven’t seen a tutorial for this that isn’t badly spelled and hard to grok, so I’ll try it.
First, include the radio group widget and and declare one. You’ll also need LayoutParams and RadioButton, so include those as well.
1 2 3 4 5 6 7 8 9 |
//SomeAndroidActivity import android.widget.RadioGroup; import android.view.ViewGroup.LayoutParams; import android.widget.RadioButton; public class SomeAndroidActivity extends Activity () { //declare a radio group RadioGroup radioGroup; } |
Inside your onCreate method, initialize the radio group.
1 2 3 4 5 6 7 8 |
//SomeAndroidActivity @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_some_android); radioGroup = (RadioGroup) findViewById(R.id.radio_selection_group); } |
R.id.radio_selection_group is referring to a radio group that’s declared in your XML file, so make sure you have that as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<!-- activity_some_android.xml --> <RelativeLayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".SomeAndroidActivity" > <RadioGroup android:id="@+id/radio_selection_group" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="76dp" android:layout_marginTop="135dp" > </RadioGroup> </RelativeLayout> |
Back in SomeAndroidActivity, create a method to dynamically add buttons to the radio group.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//SomeAndroidActivity private void addRadioButtons(int numButtons) { for(int i = 0; i < numButtons; i++) //instantiate... RadioButton radioButton = new RadioButton(this); //set the values that you would otherwise hardcode in the xml... radioButton.setLayoutParams (new LayoutParams (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); //label the button... radioButton.setText("Radio Button #" + i); radioButton.setId(i); //add it to the group. radioGroup.addView(radioButton, i); } } |
Then call that method in onCreate.
1 2 3 4 5 6 7 8 9 10 |
//SomeAndroidActivity @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_some_android); radioGroup = (RadioGroup) findViewById(R.id.radio_selection_group); int numberOfRadioButtons = 7; addRadioButtons(numberOfRadioButtons); } |
Easy pie.