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);
}
}
使用方法:
<DrawableCenterRadioButton
android:id="@+id/rb_boy"
android:drawableLeft="@drawable/boy"
android:checked="true"
android:text="男"
style="@style/rgb_sex" />
<style name="rgb_sex">
<item name="android:layout_width">0dp</item>
<item name="android:layout_height">fill_parent</item>
<item name="android:layout_weight">1</item>
<item name="android:button">@null</item>
<item name="android:drawablePadding">5dp</item>
<item name="android:background">@drawable/rbg_boy_girl_bkg</item>
<item name="android:textColor">@drawable/rbg_boy_girl</item>
<item name="android:textSize">@dimen/text_choice_title</item>
</style>
image

你可能感兴趣的:(RadioButton图片文字居中显示)