如何在RadioGroup中获取OnCheckedChangeListener

时间:2017-08-21 10:16:05

标签: android

RadioGroup提供方法" set()"对于OnCheckedChangeListener,但不是" get()"。但是我的模块必须以某种方式获得RadioGroup的OnCheckedChangeListener并用我的监听器包装它,它为客户提供行为跟踪。如何在不要求我的库用户明确将其作为参数提供的情况下获取此OnCheckedChangeListener侦听器?

问题样本:

我们可以实现方法:

void wrapMyRadioGroup(RadioGroup group,OnCheckedChangeListener listener){
     group.setOnCheckedChangeListener(new SomeCompositeListener(listener));
}

但不能这样:

void wrapMyRadioGroup(RadioGroup group){
     group.setOnCheckedChangeListener(new SomeCompositeListener(group.getOnCheckedChangeListener()));
}

而且,正如你可以猜到的那样,我们需要最后一个。

P.S。

我找到了带反射的解决方案。

  private void trackRadioGroup(RadioGroup radioGroup){
    RadioGroup.OnCheckedChangeListener listener = null;
    try {
        Field field = radioGroup.getClass().getDeclaredField("mOnCheckedChangeListener");
        field.setAccessible(true);
        Object value = field.get(radioGroup);
        if(value !=null){
            listener = (RadioGroup.OnCheckedChangeListener)value;
        }
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    radioGroup.setOnCheckedChangeListener(new SomeCompositeListener(listener));
}

感谢大家的理解和评价...

1 个答案:

答案 0 :(得分:1)

试试这个

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.cancle_booking_radio_group);

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {

            View radioButton = radioGroup.findViewById(checkedId);
            int index = radioGroup.indexOfChild(radioButton);
            switch (index) {
                case 0:
                    // perform your action here
                    break;
                case 1:
                    // perform your action here
                    break;
                case 2:
                    // perform your action here
                    break;
                case 3:
                   // perform your action here
                    break;
                case 4:
                    // perform your action here
                    break;
            }
        }
    });