RadioButton
and RadioGroup
provided by Android's standard API.
It's good so far that if you nest multiple RadioButton
s in oneRadioGroup
, only one of them can be selected at a time, but you can arrange the RadioButton
freely. Unacceptable.
As you can see in the documentation, ʻandroid.widget.RadioGroup inherits ** ʻandroid.widget.LinearLayout
**.
Everyone knows what LinearLayout is. In other words, it can only be arranged in one horizontal row or one vertical row.
why! !!
So I made it. Such a class.
FreeRadioGroup.java
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class FreeRadioGroup {
private List<RadioButton> registeredRadioButtons = new ArrayList<>();
public FreeRadioGroup(){
}
public void addChild(RadioButton rb){
if(registeredRadioButtons.contains(rb)){
Log.w("FreeRadioGroup", "RadioButton already registered. Abort registering");
}else {
registeredRadioButtons.add(rb);
rb.setOnCheckedChangeListener(OCL);
}
}
public void removeChild(RadioButton rb){
if(!registeredRadioButtons.contains(rb)){
Log.w("FreeRadioGroup", "RadioButton is not registered. Abort unregistering");
}else {
registeredRadioButtons.remove(rb);
rb.setOnClickListener(null);
}
}
public int getSelectedButtonIndex(){
for(int i=0,n=registeredRadioButtons.size();i<n;i++){
if(registeredRadioButtons.get(i).isChecked()){
return i;
}
}
return -1;
}
@Nullable
public RadioButton getSelectedButton(){
for(int i=0,n=registeredRadioButtons.size();i<n;i++){
RadioButton r = registeredRadioButtons.get(i);
if(r.isChecked()){
return r;
}
}
return null;
}
private final CompoundButton.OnCheckedChangeListener OCL = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(registeredRadioButtons.contains((RadioButton)compoundButton) && b){
for(RadioButton r : registeredRadioButtons){
if(r.equals((RadioButton)compoundButton)){
continue;
}
r.setChecked(false);
}
}
}
};
}
For the time being, you can copy it in a circle and use it.
When you register a RadioButton
that you want to register with ʻaddChild (RadioButton rb)`, only one of the registered ones is selected at the same time.
On the contrary, I think it is necessary at a level where I wonder if this is not officially implemented.
-If you try to register another listener that is called when the button status changes, it will be overwritten and cannot be used.
I'm not in trouble with this for what I use so far, so I'll think about it when I have time. Or if there is any good way, please let me know in the comments. OnClick can be used normally, so if that's all you need, there should be no problem.
Recommended Posts