繁体   English   中英

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

[英]Programatically align radio button to center in 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 

文本仅放置在中间,但不放置单选按钮,我希望文本和单选按钮都放置在中间。

在TerrilThomas的帮助下,我得以解决了这个问题:

这是解决方案:

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

不要在按钮内部传递图标,而是将其传递给compundable可绘制方法(如果可以通过任何单选按钮使用)。

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

感谢TerrilThomas,欢呼

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM