android RadioButton相关

自定义单选按钮样式

 private void setData(List v) {
        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        layoutParams.leftMargin = DisplayUtil.dip2px(this, 5);
        layoutParams.bottomMargin = DisplayUtil.dip2px(this, 10);
        int index = 0;
        for (Datas data : v) {
            RadioButton radioButton = new RadioButton(this);
            radioButton.setGravity(Gravity.CENTER_VERTICAL);
            radioButton.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
            Drawable drawable=ContextCompat.getDrawable(this, R.drawable.radiobox_select);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                                drawable.getMinimumHeight());
            radioButton.setCompoundDrawables(drawable, null, null, null);
            radioButton.setCompoundDrawablePadding(DisplayUtil.dip2px(this, 10));
            radioButton.setPadding(1, 0, 0, 0);
            radioButton.setId(index++);
            radioButton.setTag(data.tag);
            radioButton.setText(data.reason);
            radioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            radioButton.setTextColor(Color.BLACK);
            radioGroup.addView(radioButton, layoutParams);
        }
    }

可取消的单选按钮设置

public class ToggleRadioButton extends AppCompatRadioButton {
    public ToggleRadioButton(Context context) {
        this(context, null);
    }

    public ToggleRadioButton(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.radioButtonStyle);
    }

    public ToggleRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void toggle() {
        setChecked(!isChecked());
        if (!isChecked()) {
            ((RadioGroup) getParent()).clearCheck();
        }
    }
}

下面是RadioButton中源码toggle()方法注释

/**
     * {@inheritDoc}
     * 

* If the radio button is already checked, this method will not toggle the radio button. */ @Override public void toggle() { // we override to prevent toggle when the radio is already // checked (as opposed to check boxes widgets) if (!isChecked()) { super.toggle(); } }

你可能感兴趣的:(android RadioButton相关)