Radio Group의 Radio Button 그림, 텍스트 가운데 맞춤 해결 방법

1. 문제 원인: 라디오 Button의 부류인 Compound Button의 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);
		}
	}
}

좋은 웹페이지 즐겨찾기