以编程方式将RadioButton的边距或填充添加到RadioGroup中

Joh*_*son 7 java android

我想以编程方式向RadioGroup添加边距或填充但不起作用.

单选按钮:

<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" />
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

Java代码:

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

radioGroup.addView(radioButtonView);
Run Code Online (Sandbox Code Playgroud)

我试图用LayoutParamsdividerPadding,但它不工作

例

小智 14

试试这个

  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);
Run Code Online (Sandbox Code Playgroud)


小智 10

单选按钮的边距和填充:

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);
Run Code Online (Sandbox Code Playgroud)

RadioGroup 的边距和填充是相同的,只有 LayoutParams 的类型会不同(不是 RadioGroup.LayoutParams)但是你的 RadioGroup 的父布局是什么:LinearLayout.LayoutParams 或 RelativeLayout.LayoutParams 或 FrameLayout.LayoutParams 等。你明白了.

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(left, top, right, bottom);
radioGroup.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)

左、上、右、下以​​像素为单位,因此您应该将 DP 转换为 PX,就像在这个答案中一样