好记性不如烂笔杆-android学习笔记<三> RadioGroup 和 CheckBox的使用
8,//RadioGroup 和 CheckBox的使用
xml文件中:
1 <RadioGroup 2 android:id="@+id/genderGroup" 3 android:layout_width="wrap_content" 4 android:layout_height="wrap_content" 5 android:orientation="vertical"> 6 7 <RadioButton 8 android:id="@+id/femaleButton" 9 android:layout_width="wrap_content" 10 android:layout_height="wrap_content" 11 android:text="@string/female"/> 12 <RadioButton 13 android:id="@+id/maleButton" 14 android:layout_width="wrap_content" 15 android:layout_height="wrap_content" 16 android:text="@string/male"/> 17 </RadioGroup> 18 <CheckBox 19 android:id="@+id/swim" 20 android:layout_width="wrap_content" 21 android:layout_height="wrap_content" 22 android:text="@string/swimBox" 23 /> 24 <CheckBox 25 android:id="@+id/run" 26 android:layout_width="wrap_content" 27 android:layout_height="wrap_content" 28 android:text="@string/runBox" 29 /> 30 <CheckBox 31 android:id="@+id/read" 32 android:layout_width="wrap_content" 33 android:layout_height="wrap_content" 34 android:text="@string/readBox" 35 />
Java文件中
1 //为RadioButton添加监听器,一组按钮对应一个监听器 2 genderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 3 4 @Override 5 public void onCheckedChanged(RadioGroup group, int checkedId) { 6 if(famaleButton.getId() == checkedId){ 7 System.out.println("famale"); 8 Toast.makeText(RadioTest.this, "famale", Toast.LENGTH_SHORT).show(); 9 } 10 else if(maleButton.getId() == checkedId){ 11 System.out.println("male"); 12 Toast.makeText(RadioTest.this, "male", Toast.LENGTH_SHORT).show(); 13 } 14 } 15 }); 16 //为多选框添加监听器,每个checkbox对应一个监听器 17 swimBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 18 19 @Override 20 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 21 if(isChecked){ 22 System.out.println("swim is checked"); 23 } 24 else 25 { 26 System.out.println("swim is unchecked"); 27 } 28 } 29 }); 30 runBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 31 32 @Override 33 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 34 if(isChecked){ 35 System.out.println("run is checked"); 36 } 37 else 38 { 39 System.out.println("run is unchecked"); 40 } 41 } 42 }); 43 readBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 44 45 @Override 46 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 47 if(isChecked){ 48 System.out.println("read is checked"); 49 } 50 else 51 { 52 System.out.println("read is unchecked"); 53 } 54 } 55 }); 56 }