如下图像是整体的布局
这是main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /><RadioGroup android:id="@+id/gender" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > <RadioButton android:id="@+id/man" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/man" /> <RadioButton android:id="@+id/woman" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/woman" /></RadioGroup><CheckBox android:id="@+id/run" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/run" /><CheckBox android:id="@+id/sing" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/sing" /><CheckBox android:id="@+id/dance" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/dance" /></LinearLayout>
这是RadioButton触发事件的核心代码
gender = (RadioGroup)findViewById(R.id.gender); man = (RadioButton)findViewById(R.id.man); woman = (RadioButton)findViewById(R.id.woman); gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub if(man.getId()==checkedId){ //System.out.println("男"); Toast.makeText(radioTest.this, "我是帅哥", Toast.LENGTH_LONG).show(); }else if(woman.getId()==checkedId){ //System.out.println("女"); Toast.makeText(radioTest.this, "我是美女", Toast.LENGTH_LONG).show(); } } });
这是CheckBox的触发事件的核心代码
run.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if(isChecked){ //System.out.println("run checked"); Toast.makeText(radioTest.this, "感觉很好!", Toast.LENGTH_LONG).show(); }else{ //System.out.println("run unchecked"); Toast.makeText(radioTest.this, "坑爹啊!", Toast.LENGTH_LONG).show(); } } });
从中我们可以看到单选按钮触发事件是绑定到了RadioGroup上面,而多选按钮是绑定到了每一个多选按钮上。此外,我们看到还有Toast,这是一个提示消息,就像上面图像里的一样,用法很简单,就是一句话
Toast.makeText(radioTest.this, "我是美女", Toast.LENGTH_LONG).show();
我们依葫芦画瓢就可以了