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 2nd one is below that, the third to the right of the 1st one and the 4th one underneath that. In other words, I want to create a group where the radiobuttons are laid out in a square of sorts. I think if I set the orientation of the group to be vertical, then all the radiobuttons will be in a straight line. If, on the other hand, I set the orientation to horizontal, then, again, the radiobuttons will all be in a straight line, going horizontal. Is there a way to do what I want or am I forced to set up two separate RadioGroups
, both to horizontal orientation?
Asked
Active
Viewed 1.3k times
5

LuxuryMode
- 33,401
- 34
- 117
- 188
-
you can use the RelativeLayout instead of LinearLayout – Pratik Jun 13 '11 at 14:53
-
1@Pratik hows that going to help? That will help me set up the Group relative to something else, but what about the buttons relative to each other? – LuxuryMode Jun 13 '11 at 15:03
2 Answers
32
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.

Matt
- 774
- 8
- 16
-
Awesome answer Matt, Can you please explain how to get Id of selected radio button, I tried but I failed. Waiting for your valuable answer. Thanks. – MohanRaj S May 26 '17 at 06:55
0
You should subclass from RadioGroup and override onLayout() method.

woodshy
- 4,085
- 3
- 22
- 21
-
Thanks! Do you have an example of what the override would look like to accomplish wha I'm trying to do? – LuxuryMode Jun 13 '11 at 15:19
-
you could figure out how to implement onLayout from Roman Nurik's dashboard view: https://gist.github.com/882650 – woodshy Jun 13 '11 at 15:23