I tried to implement a radiogroup with four togglebuttons. The desired behaviour is the typical radio group behaviour: One button is preselected, if the user clicks another button, the previous one is unselected and the new one selected instead. If the user clicks a selected button again nothing should happen since its not allowed to have none of the buttons selected. And thats where I got problems. I followed the solution to this question: Android: How to get a radiogroup with togglebuttons?
Unfortunately the user is still able to deselect the active button. How can I prevent this?
Heres my code:
The onClick Listener for the ToggleButtons:
/**
* Handler for onClick Events.
*/
@Override
public void onClick(View v) {
if (viewListener == null) {
return;
}
if (v == tb_one|| v == tb_two|| v == tb_three|| v == tb_four) {
((RadioGroup) v.getParent()).check(v.getId());
}
else {
super.onClick(v);
}
}
My custom OnCheckedChangeListener:
/**
* The listener for a checked change event of the toggle buttons.
*/
static final RadioGroup.OnCheckedChangeListener ToggleListener = new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final RadioGroup radioGroup, final int i) {
//if one button is checked, uncheck all others
for (int j = 0; j < radioGroup.getChildCount(); j++) {
final ToggleButton view = (ToggleButton) radioGroup.getChildAt(j);
view.setChecked(view.getId() == i);
}
}
};
And heres where I add the listeners: (its in the onFinishInflate method)
((RadioGroup) findViewById(R.id.instant_toggleGroup_mode))
.setOnCheckedChangeListener(ToggleListener);
tb_one = (ToggleButton) findViewById(R.id.instant_tb_one);
tb_one.setOnClickListener(this);
tb_two = (ToggleButton) findViewById(R.id.instant_tb_two);
tb_two.setOnClickListener(this);
tb_three = (ToggleButton) findViewById(R.id.instant_tb_three);
tb_three.setOnClickListener(this);
tb_four = (ToggleButton) findViewById(R.id.instant_tb_four);
tb_four.setOnClickListener(this);
Would be great if someone could point out the solution to me!