android 中关于多行RadioGroup只选择一个RadioButton的解决方法

今天博主在项目中遇到了一个问题,有多行数据用RadioGroup来显示,但是,只能选中这个多行RadioGroup中的一个radiobutton,刚开始我想的是用一个radiogroup做最外层,然后里面用LinearLayout来包裹这些radiobutton,以便于进行orientation属性的设置,但是,这样设置完成后,却不能实现博主的功能,无奈,只得自定义。代码如下:

public class RadioGroupUtils extends RadioGroup {
    private OnCheckedChangeListener onCheckedChangeListener;

    public RadioGroupUtils(Context context) {
        super(context);
    }

    public RadioGroupUtils(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
        onCheckedChangeListener = listener;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void addView(final View child, int index, ViewGroup.LayoutParams params) {
        if (child instanceof ViewGroup) {
            int childCount = ((ViewGroup) child).getChildCount();
            for (int i = 0; i < childCount; i++) {
                View view = ((ViewGroup) child).getChildAt(i);
                if (view instanceof RadioButton) {
                    final RadioButton button = (RadioButton) view;
                    (button).setOnTouchListener(new OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            (button).setChecked(true);
                            checkRadioButton(button);
                            if (onCheckedChangeListener != null) {
                                onCheckedChangeListener.onCheckedChanged(RadioGroupUtils.this, button.getId());
                            }
                            return true;
                        }
                    });
                }
            }
        }
        super.addView(child, index, params);
    }

    private void checkRadioButton(RadioButton radioButton) {
        View child;
        int radioCount = getChildCount();
        for (int i = 0; i < radioCount; i++) {
            child = getChildAt(i);
            if (child instanceof RadioButton) {
                if (child == radioButton) {
                    // do nothing
                } else {
                    ((RadioButton) child).setChecked(false);
                }
            } else if (child instanceof ViewGroup) {
                int childCount = ((ViewGroup) child).getChildCount();
                for (int j = 0; j < childCount; j++) {
                    View view = ((ViewGroup) child).getChildAt(j);
                    if (view instanceof RadioButton) {
                        final RadioButton button = (RadioButton) view;
                        if (button == radioButton) {
                            // do nothing
                        } else {
                            (button).setChecked(false);
                        }
                    }
                }
            }
        }
    }
}

完美解决!博主是新手,大佬勿喷。

你可能感兴趣的:(android,开发)