Question

I have about 60 radio groups that I need to register a listener for. Currently this is how I do it:

    RadioGroup rg1 = (RadioGroup) getView().findViewById(R.id.rdoGrp1);
    rg1.setOnCheckedChangeListener(this);
    rg1 = (RadioGroup) getView().findViewById(R.id.rdoGrp2);
    rg1.setOnCheckedChangeListener(this);
    rg1 = (RadioGroup) getView().findViewById(R.id.rdoGrp3);
    rg1.setOnCheckedChangeListener(this);

and so on for the 60 radio groups. Is there a way to set all radio groups on the fragment to register to a common listener in a single statement or two without having to type out this much code? Thanks

Was it helpful?

Solution

If all the RadioGroup elements share the same parent, you could iterate using ViewGroup.getChildAt and ViewGroup.getChildCount. Something like this:

ViewGroup parent = (ViewGroup) findViewById(R.id.ParentViewId);
for (int i = 0; i < parent.getChildCount(); i++) {
    View currentView = parent.getChildAt(i);
    if (currentView instanceof RadioGroup) {
        ((RadioGroup) currentView).setOnCheckedChangeListener(this);
    }
}

OTHER TIPS

An easy solution would be to create a method in your activity or whatever class you are writing, something like this:

private void registerListenerToGroup(int groupId) {
    RadioGroup rg = (RadioGroup) getView().findViewById(groupId);
    rg.setOnCheckedChangeListener(this);
}

Then, call this method from your code like this:

registerListenerToGroup(R.id.rdoGrp1);
registerListenerToGroup(R.id.rdoGrp2);
registerListenerToGroup(R.id.rdoGrp3);
//etc.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top