在这种情况下,android分组单选按钮

在这种情况下,android分组单选按钮,android,android-radiobutton,Android,Android Radiobutton,在我的应用程序中,我从布局文件夹中展开视图: <RelativeLayout android:layout_width="match_parent" android:background="#468966" android:layout_height="40dp"> <RadioButton android:id="@+id/radio" android:layout_height="40dp" android:layout_width="40dp"

在我的应用程序中,我从布局文件夹中展开视图:

<RelativeLayout
android:layout_width="match_parent"
android:background="#468966"
android:layout_height="40dp">
<RadioButton
    android:id="@+id/radio"
    android:layout_height="40dp"
    android:layout_width="40dp"
    android:layout_alignParentRight="true"
    android:layout_marginRight="10dp"
    android:layout_centerVertical="true" />

<TextView
    android:id="@+id/optionText"
    android:layout_height="40dp"
    android:layout_width="wrap_content"
    android:layout_centerVertical="true"
    android:textSize="16dp"
    android:textColor="#002F2F"
    android:gravity="center_vertical"
    android:layout_toLeftOf="@id/radio"
    android:layout_marginRight="10dp" />
  </RelativeLayout>


并将其动态添加到线性布局中。现在,如何对这些视图的单选按钮进行分组,以便一次只能选择其中一个?

首先,您需要在XML文件中有一个RadioGroup控件

<RadioGroup 
android:id="@+id/radiogroup"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true" 
android:orientation="vertical" />

然后您可以以这种方式动态添加到它

RadioGroup rgp= (RadioGroup) findViewById(R.id.radiogroup);
 RadioGroup.LayoutParams rprms;
 for(int i=0;i<3;i++){
 RadioButton radioButton = new RadioButton(this);
 radioButton.setText("new"+i); radioButton.setId("rbtn"+i); 
rprms= new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
 rgp.addView(radioButton, rprms); 
}
RadioGroup rgp=(RadioGroup)findViewById(R.id.RadioGroup);
RadioGroup.LayoutParams rprms;

对于(int i=0;i
首先,您需要在XML文件中有一个RadioGroup控件。
。哪个XML文件?!您将在其中动态添加用于分组的单选按钮