在RadioButton,内有时候会用到左面放图片,右面放文字。
例如:
一般图片都居左显示,达不到以上效果,我们需要自定义RadioButton,已达到图片和文字居中显示
如下:
public class DrawableCenterRadioButton extends RadioButton { public DrawableCenterRadioButton(Context context) { super(context); } public DrawableCenterRadioButton(Context context, AttributeSet attrs) { super(context, attrs); } public DrawableCenterRadioButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { Drawable[] drawables = getCompoundDrawables(); if (drawables != null) { Drawable drawableLeft = drawables[0]; if (drawableLeft != null) { float textWidth = getPaint().measureText(getText().toString()); int drawablePadding = getCompoundDrawablePadding(); int drawableWidth = 0; drawableWidth = drawableLeft.getIntrinsicWidth(); float bodyWidth = textWidth + drawableWidth + drawablePadding; canvas.translate((getWidth() - bodyWidth) / 2, 0); } } super.onDraw(canvas); } }