1.创建一个attrs.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CompoundButton">
<attr name="android:button" />
<attr name="textColor" format="color"/>
<attr name="textSize" format="dimension"/>
<attr name="text" format="string"/>
</declare-styleable>
</resources>
2.继承RadioButton
public class MyRadioButton extends RadioButton {
public MyRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
paint=new TextPaint(Paint.ANTI_ALIAS_FLAG);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CompoundButton, 0, 0);
buttonDrawable = a.getDrawable(R.styleable.CompoundButton_android_button);
// setButtonDrawable(android.R.id.empty);
setButtonDrawable(android.R.color.transparent);
float textSize = a.getDimension(R.styleable.CompoundButton_textSize, 36);
text=a.getString(R.styleable.CompoundButton_text);
paint.density = getResources().getDisplayMetrics().density;
paint.setTextSize(textSize);
a.recycle();
}
Drawable buttonDrawable;
TextPaint paint;
String text;
@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 textWidth=(int)paint.measureText(text);
int buttonLeft = (getWidth() - buttonWidth-textWidth) / 2;
buttonDrawable.setBounds(buttonLeft, y, buttonLeft+buttonWidth, y + height);
buttonDrawable.draw(canvas);
}
}
}
3.使用
<com.vnetoo.xdmpstudent.tools.MyRadioButton
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:text="在线课程"
vnetoo:text="在线课程"
android:textSize="20sp"
vnetoo:textSize="20sp"
android:textColor="@color/black"
vnetoo:textColor="@color/black"
android:paddingLeft="20dp"
style="@style/NowCourseButton"
android:layout_height="match_parent"/>