Search code examples
javaandroidradio-button

Add padding to the left of radio button drawable


I am trying to add padding to the left of radio button. But the padding is actually added between the drawable and text.

What i get: Space between drawable and text
enter image description here

What i want: Space to the left of drawable
enter image description here

My method for creating radio button:

private RadioButton createRadioButton(String text) {
    RadioButton btn = new RadioButton(requireContext());

    btn.setId(View.generateViewId());
    btn.setText(text);
    btn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
    btn.setTextColor(answerButtonColor);
    btn.setButtonTintList(answerButtonColor);

    int pxHorizontal = Utils.convertDpToPx(requireContext(), 24);
    int pxVertical = Utils.convertDpToPx(requireContext(), 16);
    btn.setPadding(pxHorizontal, pxVertical, pxHorizontal, pxVertical);

    btn.setLayoutParams(new RadioGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
    ));

    return btn;
}

Is there a way how to add padding to the left of the radio button?


Solution

  • RadioButton is a subclass of CompundButton, so we get drawable on the compound button and add inset to it.

    val compoundButtonDrawable = CompoundButtonCompat.getButtonDrawable(radioButton1)
    val insetDrawable = InsetDrawable(compoundButtonDrawable, 32, 0, 0, 0)
    radioButton1.buttonDrawable = insetDrawable