문제

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

도움이 되었습니까?

해결책

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);
    }
}

다른 팁

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.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top