18

I would like to add margin or padding to a RadioGroup programmatically but it not working.

RadioButton:

<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/ic_fruit"
    android:button="@null"
    android:checked="false" />

RadioGroup:

<RadioGroup
            android:id="@+id/radio_group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:orientation="horizontal">

</RadioGroup>

Java code:

RadioButton radioButtonView = (RadioButton) getActivity().getLayoutInflater().inflate(R.layout.radio_button, null);

radioGroup.addView(radioButtonView);

I tried to use LayoutParams and dividerPadding but it not works

example

Johnny
  • 2,989
  • 4
  • 17
  • 28

2 Answers2

41

Try this

  RadioButton radioButtonView = (RadioButton) getLayoutInflater().inflate(R.layout.radio_button, null, false);
  RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
  params.setMargins(15, 15, 15, 15);
  radioButtonView.setLayoutParams(params);
  radioGroup.addView(radioButtonView);
ShekharKG
  • 675
  • 6
  • 11
  • 1
    Thank you! It works with a new `LayoutParams`. I tried to get the current `LayoutParams` with `getLayoutParams()` and it was not working. Now it works thanks! – Johnny Dec 19 '16 at 10:52
11

Margin & Padding for a RadioButton:

RadioButton rd = new RadioButton(getActivity());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(left, top, right, bottom);
rd.setLayoutParams(params);
rd.setPadding(left, top, right, bottom);
radioGroup.addView(rd);

Margin and padding for the RadioGroup are the same, only the type of LayoutParams will be different (not RadioGroup.LayoutParams) but what your RadioGroup's parent layout is: LinearLayout.LayoutParams or RelativeLayout.LayoutParams or FrameLayout.LayoutParams, etc. You get the idea.

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(left, top, right, bottom);
radioGroup.setLayoutParams(params);

Left, top, right, bottom are in pixels, so you should transform your DP into PX, like in this answer

Community
  • 1
  • 1
Monica O.
  • 326
  • 2
  • 8