I have tried this code..It will display three radio buttons in a single row when the emulator starts. But I need a button event for this. i.e; if I click the button, it shou
This is the way to do this:
RadioGroup rgp = (RadioGroup) findViewById(R.id.radio_group);
int buttons = 5;
for (int i = 1; i <= buttons ; i++) {
RadioButton rbn = new RadioButton(this);
rbn.setId(View.generateViewId());
rbn.setText("RadioButton" + i);
rgp.addView(rbn);
}
But what if you need to do this horizontally, just add the orientation (the default value is vertical) with setOrientation() method:
RadioGroup rgp = (RadioGroup) findViewById(R.id.radio_group);
rgp.setOrientation(LinearLayout.HORIZONTAL);
int buttons = 5;
for (int i = 1; i <= buttons; i++) {
RadioButton rbn = new RadioButton(this);
rbn.setId(View.generateViewId());
rbn.setText("RadioButton" + i);
rbn.setLayoutParams(params);
rgp.addView(rbn);
}
This is the complete code:
first of all defining inside our Layout the RadioGroup:
The code into the MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Defining 5 buttons.
int buttons = 5;
AppCompatRadioButton[] rb = new AppCompatRadioButton[buttons];
RadioGroup rgp = (RadioGroup) findViewById(R.id.radio_group);
rgp.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 1; i <= buttons; i++) {
RadioButton rbn = new RadioButton(this);
rbn.setId(View.generateViewId());
rbn.setText("RadioButton" + i);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f);
rbn.setLayoutParams(params);
rgp.addView(rbn);
}
}
}