Setting Up A Radiogroup Programmatically
I'd like to create a custom View which contains a RadioGroup. Inside of the RadioGroup I'd like the RadioButtons to be set up so that the first RadioButton is at the top left, the
Solution 1:
Try processing the RadioButtons
without the use of RadioGroup
.
Wire-up the individual RadioButtons
and hold them in an ArrayList<RadioButton>
.
List<RadioButton> radioButtons = new ArrayList<RadioButton>();
radioButtons.add( (RadioButton)findViewById(R.id.button1) );
radioButtons.add( (RadioButton)findViewById(R.id.button2) );
radioButtons.add( (RadioButton)findViewById(R.id.button3) );
etc.
Set an OnCheckedChangeListener
for each RadioButton
.
for (RadioButton button : radioButtons){
button.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) processRadioButtonClick(buttonView);
}
});
}
Then create a method to uncheck the unselected RadioButtons
.
private void processRadioButtonClick(CompoundButton buttonView){
for (RadioButton button : radioButtons){
if (button != buttonView ) button.setChecked(false);
}
}
Using this approach, the RadioButtons
can be located anywhere within the XML layout.
Solution 2:
You should subclass from RadioGroup and override onLayout() method.
Post a Comment for "Setting Up A Radiogroup Programmatically"