以编程方式将单选按钮对齐到无线电组中心

时间:2013-08-29 06:41:52

标签: android radio-button center radio-group

我有一个需要放在收音机组中心的单选按钮。

这是我的代码:

RadioImageButton RadioImageButton = new RadioImageButton(activity);
    RadioImageButton.setGravity(Gravity.CENTER);
    RadioImageButton.setId(buttonId);
    RadioImageButton.setTextColor(Color.BLACK);
    RadioImageButton.setButtonDrawable(icon); // this is where i am replacing the default circle with an image
    RadioImageButton.setBackgroundDrawable(drawable);
    RadioGroup.LayoutParams radioImageButtonParams = new RadioGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.MATCH_PARENT, 1f);
    radioImageButtonParams.setMargins(0, 0, 1, 0);

    RadioGroup.addView(RadioImageButton, radioImageButtonParams);

在RadioImageButton类中

Drawable image;

    public RadioImageButton(Context context) {
    super(context);
    setButtonDrawable(android.R.color.transparent);
    }

    @Override
    protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (image != null) {
        image.setState(getDrawableState());

        final int verticalGravity = getGravity() & Gravity.VERTICAL_GRAVITY_MASK;
        final int height = image.getIntrinsicHeight();

        int y = 0;

        switch (verticalGravity) {
        case Gravity.BOTTOM:
        y = getHeight() - height;
        break;
        case Gravity.CENTER_VERTICAL:
        y = (getHeight() - height) / 2;
        break;
        }

        int buttonWidth = image.getIntrinsicWidth();
        int buttonLeft = (getWidth() - buttonWidth) / 3;
        image.setBounds(buttonLeft, y, buttonLeft + buttonWidth, y + height);
        image.draw(canvas);
    }
    }

目前它是这样的:

radiobutton  ------  text 

文本只放在中心但不是单选按钮我希望文本和单选按钮都放在中心。

1 个答案:

答案 0 :(得分:1)

在TerrilThomas的帮助下,我能够解决这个问题:

以下是解决方案:

RadioImageButton.setButtonDrawable(icon); // Not proper way

不要传递按钮内的图标而是将其传递给compund drawable方法,如果任何radiobutton它会做好。

RadioImageButton.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom)// use this to set the icon

感谢TerrilThomas,欢呼声