首先,在res下面新建一個文件夾layout,在layout下面新建一個xml文件:radiogroup.xml文件
文件內容如下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/encodioninfo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="選中編碼" /> <RadioGroup android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:checkedButton="@+id/utf8" android:id="@+id/encoding"> <RadioButton android:id="@+id/utf8" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="UTF-8"/> <RadioButton android:id="@+id/gbk" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="gbk"/> <RadioButton android:id="@+id/gbk2318" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="gbk2318"/> </RadioGroup> <TextView android:id="@+id/sexinfo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="選擇性別" /> <RadioGroup android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:checkedButton="@+id/man" android:id="@+id/sex"> <RadioButton android:id="@+id/man" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="男"/> <RadioButton android:id="@+id/woman" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="女"/> </RadioGroup> </LinearLayout>
再新建一個RadioGroupActivity,並在這個activity里面設置radio的選中點擊事件,並將選中點擊事件的內容顯示出來
public class RadioGroupActivity extends Activity { private RadioGroup radiogroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.radiogroup); radiogroup =(RadioGroup)this.findViewById(R.id.encoding); radiogroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub //獲取選中的radiobutton內容 group.getCheckedRadioButtonId() RadioButton radiobutton = (RadioButton)RadioGroupActivity.this.findViewById(group.getCheckedRadioButtonId()); Toast.makeText(getApplicationContext(),"選中的內容是"+ radiobutton.getText().toString(),Toast.LENGTH_LONG).show(); } }); } }
效果