I have a custom view for radio buttons in the XML layout file with ConstraintLayout. I need to group those radio buttons. But when I try to envelop that ConstraintLayout with the Radio group, it does not group the buttons and all options are getting selected.
Asked
Active
Viewed 144 times
0
a_local_nobody
- 7,360
- 5
- 25
- 45
Sweta Jain
- 1,884
- 2
- 14
- 34
-
Why not make a custom view? Your layout is way beautiful to use the plain old RadioGroup logic and there are lot of articles to give you that allow "one of many" selection feature you get in a radio group – gtxtreme Sep 07 '21 at 09:12
-
@gtxtreme Do you mean that using a radio group for this custom view is not possible using old RadioGroup logic? – Sweta Jain Sep 07 '21 at 09:17
-
I have limited experience with RadioGroup as such but I know we use it for that "just one of many" selection feature and the customisation in RadioGroup is limited as far as the look and feel is concerned – gtxtreme Sep 07 '21 at 09:21
-
https://bitbucket.org/ManuelMato/customradiobutton/src/develop/app/src/ Did you try looking at this? Seems like something similar to your use case – gtxtreme Sep 07 '21 at 09:23
1 Answers
0
RadioButtons need to be the direct children of a RadioGroup in order for the grouping functionality to work. A RadioGroup is just a special LinearLayout that implements the grouping functionality for all the children added that are RadioButtons. You can simply implement your own grouping functionality by adding the RadioButtons to a List and then implementing OnCheckedChangeListener and setting it on each of the RadioButtons as follows:
private final List<RadioButton> radioButtons = new ArrayList<>();
private int checkedId;
private void setRadioButton(RadioButton radioButton) {
radioButtons.add(radioButton);
radioButton.setOnCheckedChangeListener(mOnCheckedChangeListener);
}
private final CompoundButton.OnCheckedChangeListener mOnCheckedChangeListener =
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
checkedId = buttonView.getId();
}
for (RadioButton radioButton : radioButtons) {
if (radioButton.getId() != checkedId) {
radioButton.setChecked(false);
}
}
}
};
wambada
- 99
- 6