Android单选钮的setOnCheckedChangeListener事件
首先,在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(); } }); } }
效果