重写RadioButton的onDraw()方法

public class CenterRadioButton extends RadioButton {

	public CenterRadioButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		TypedArray a = context.obtainStyledAttributes(attrs,
				R.styleable.CompoundButton, 0, 0);
		buttonDrawable = a.getDrawable(1);
		setButtonDrawable(android.R.id.empty);
	}

	Drawable buttonDrawable;

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		if (buttonDrawable != null) {
			buttonDrawable.setState(getDrawableState());
			final int verticalGravity = getGravity()
					& Gravity.VERTICAL_GRAVITY_MASK;
			final int height = buttonDrawable.getIntrinsicHeight();

			int y = 0;

			switch (verticalGravity) {
			case Gravity.BOTTOM:
				y = getHeight() - height;
				break;
			case Gravity.CENTER_VERTICAL:
				y = (getHeight() - height) / 2;
				break;
			}

			int buttonWidth = buttonDrawable.getIntrinsicWidth();
			int buttonLeft = (getWidth() - buttonWidth) / 2;
			buttonDrawable.setBounds(buttonLeft, y, buttonLeft + buttonWidth, y
					+ height);
			buttonDrawable.draw(canvas);
		}
	}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>    
     <declare-styleable name="CompoundButton">
        <attr name="android:button" />
    </declare-styleable>
</resources>

你可能感兴趣的:(重写RadioButton的onDraw()方法)