RadioButton之互斥选择和Toast显示
前言:
RadioButton用来单选并且用Toast来进行提示所选内容
RadioButton标签单独写的时候不能出现互斥现象,代码如下
1 <RadioButton 2 android:layout_height="wrap_content" 3 android:layout_width="wrap_content" 4 android:text="男" 5 android:id="@+id/nan"/> 6 <RadioButton 7 android:layout_height="wrap_content" 8 android:layout_width="wrap_content" 9 android:text="女" 10 android:id="@+id/nv"/>
效果:
此时在屏幕中并不会互斥的选择,这是和我们意愿不符合,这是应该把这两个标签加在<RadioGroup><RadioGroup/>中,来实现可以互斥选择的效果
代码如下
1 <RadioGroup 2 android:layout_height="wrap_content" 3 android:layout_width="wrap_content"> 4 <RadioButton 5 android:layout_height="wrap_content" 6 android:layout_width="wrap_content" 7 android:text="男" 8 android:id="@+id/nan"/> 9 <RadioButton 10 android:layout_height="wrap_content" 11 android:layout_width="wrap_content" 12 android:text="女" 13 android:id="@+id/nv"/> 14 </RadioGroup>
这样就可以实现互斥选择了
接下来实现当选择男是提示你选择男,
在RadioAcivity中的代码为
1 public class RadioActivity extends Activity { 2 private RadioButton nan, nv; 3 4 @Override 5 protected void onCreate(Bundle savedInstanceState) { 6 7 // TODO Auto-generated method stub 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.radio); 10 nan = (RadioButton) findViewById(R.id.nan); 11 nv = (RadioButton) findViewById(R.id.nv); 12 nan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 13 14 @Override 15 public void onCheckedChanged(CompoundButton buttonView, 16 boolean isChecked) { 17 // TODO Auto-generated method stu 18 if (isChecked) { 19 Toast.makeText(RadioActivity.this, 20 "您选择的是:" + nan.getText(), 1).show(); 21 } 22 23 } 24 }); 25 nv.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 26 27 @Override 28 public void onCheckedChanged(CompoundButton buttonView, 29 boolean isChecked) { 30 // TODO Auto-generated method stu 31 if (isChecked) { 32 Toast.makeText(RadioActivity.this, "您选择的是:" + nv.getText(), 33 1).show(); 34 } 35 36 } 37 }); 38 } 39 40 }
我们知道RadioButton和CheckBox都为CompoundButton的子类,按钮有按钮的监听器,RadioButton也有自己的监听器,在初始化控件后,开始设置监听器(setCheckedChangeLintener),如12行和25行,我们使用匿名类来实现监听事件,因为onCheckedChangeListener是在CompoundButton下定义的,所以实例化onCheckedChangeListener对象,要加外部类名【此知识点是Java内部类知识点】,然后重写onCheckedChanged方法,这方法有两个参数一个是 Compound buttonView 一个是boolean isChecked当我们点过RadioButton时,isChecked为true
接下来就是用Toast来显示,注意第一个参数不是this 而是RadioActivity.this