1.出现问题原因:RadioButton的父类CompoundButton里的onDraw方法,draw出来的内容,只有默认的水平靠左,没有水平居中的,其源代码如下,各位帅哥请看:
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); final Drawable buttonDrawable = mButtonDrawable; if (buttonDrawable != null) { 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; } buttonDrawable.setBounds(0, y, buttonDrawable.getIntrinsicWidth(), y + height); buttonDrawable.draw(canvas); } }2.解决方法:继承RadioButton构建自己的MyRadioButton类:
public class MyRadioButton extends RadioButton{ private Context context; private Drawable mButtonDrawable; private int mButtonResource; public MyRadioButton(Context context) { super(context); this.context = context; } public MyRadioButton(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } @Override public void setButtonDrawable(int resid) { if (resid != 0 && resid == mButtonResource) { return; } mButtonResource = resid; Drawable d = null; if (mButtonResource != 0) { d = getResources().getDrawable(mButtonResource); } setButtonDrawable(d); } @Override public void setButtonDrawable(Drawable d) { if (d != null) { if (mButtonDrawable != null) { mButtonDrawable.setCallback(null); unscheduleDrawable(mButtonDrawable); } d.setCallback(this); d.setState(getDrawableState()); d.setVisible(getVisibility() == VISIBLE, false); mButtonDrawable = d; mButtonDrawable.setState(null); setMinHeight(mButtonDrawable.getIntrinsicHeight()); } refreshDrawableState(); } // 核心代码部分 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); final Drawable buttonDrawable = mButtonDrawable; if (buttonDrawable != null) { final int verticalGravity = getGravity() & Gravity.VERTICAL_GRAVITY_MASK; final int height = buttonDrawable.getIntrinsicHeight(); final int width = buttonDrawable.getIntrinsicWidth(); int y = 0; switch (verticalGravity) { case Gravity.BOTTOM: y = getHeight() - height; break; case Gravity.CENTER_VERTICAL: y = (getHeight() - height) / 2; break; } int x = 0; x = (getWidth() - width) / 2; buttonDrawable.setBounds(x, y, x + width, y + height); buttonDrawable.draw(canvas); } } }