ConstraintLayout, RadioGroup and two columns of RadioButton

Andy Strife picture Andy Strife · Nov 9, 2016 · Viewed 7.5k times · Source

I have a ConstraintLayout as a root Layout and it's fine.
However I now have a RadioGroup where I have to make two columns of RadioButtons within it. Since ConstraintLayout is about getting the rid of Nested Layouts, I thought it would be fine placing those RadioButtons in the RadioGroup and place them appropriately.
Turns out having a ConstraintLayout as a Root layout, Containing the RadioGroup, doesn't seem to change anything.
But maybe I'm wrong.

How would you guys achieve having two rows of RadioButtons within a RadioGroup, which is inside a ConstraintLayout?

Cheers

Answer

Karakuri picture Karakuri · Nov 9, 2016

Views have to use layout attributes of their direct parent. You can't, for instance, have RadioButtons with layout_constraints, because the direct parent is a RadioGroup and RadioGroup doesn't know how to interpret those attributes.

RadioGroup extends LinearLayout, so the best you can do with a single RadioGroup is a single row or column of RadioButtons. You could have two RadioGroups in your layout and in your java code listen for changes on both.

private RadioGroup mGroup1; // init in onCreate
private RadioGroup mGroup2; // init in onCreate

private OnCheckedChangedListener mCheckListener = new OnCheckedChangedListener() {

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // To make it appear as if the two groups are one large group,
        // checking something in either should clear the check in the other.
        RadioGroup otherGroup = group == mGroup1 ? mGroup2 : mGroup1;
        otherGroup.clearCheck();

        // do something with checkedId
    }
}