以编程方式将无线电按钮的边距或填充添加到无线电组中

2022-09-03 03:40:38

我想以编程方式向 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" />

无线电组:

<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 代码:

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

radioGroup.addView(radioButtonView);

我试图使用,但它不起作用LayoutParamsdividerPadding

example


答案 1

试试这个

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

答案 2

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

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

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


推荐