Question

I have a radio button that needs to placed in center of radio group.

Here is my code:

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);

In RadioImageButton class

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);
    }
    }

Currently its like this :

radiobutton  ------  text 

The text is only placed in center but not the radio button i want the text and the radio button both to be placed in center.

Was it helpful?

Solution

With the help on TerrilThomas i was able to solve the issue:

Here is the solution :

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

do not pass the icon inside the button instead pass it on the compund drawable method if any of the radiobutton it will do good.

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

Thanks to TerrilThomas , cheers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top