1

我有一个单选按钮,需要放置在单选组的中心。

这是我的代码:

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 

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

4

1 回答 1

1

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

这是解决方案:

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

不要在按钮内传递图标,而是将它传递给 compund drawable 方法,如果有任何单选按钮会很好的话。

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

感谢 TerrilThomas ,干杯

于 2013-08-29T07:12:08.583 回答