让CheckBox二选一
布局文件
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 tools:context="com.example.test.MainActivity" > 6 7 <CheckBox 8 android:id="@+id/football" 9 android:layout_width="wrap_content" 10 android:layout_height="wrap_content" 11 android:layout_alignParentLeft="true" 12 android:layout_below="@+id/gender" 13 android:text="足球" /> 14 <CheckBox 15 android:id="@+id/basketball" 16 android:layout_width="wrap_content" 17 android:layout_height="wrap_content" 18 android:layout_alignParentLeft="true" 19 android:layout_below="@+id/football" 20 android:text="蓝球" /> 21 22 </RelativeLayout>
这是代码:
1 package com.example.test; 2 3 import android.os.Bundle; 4 import android.support.v7.app.ActionBarActivity; 5 import android.widget.CheckBox; 6 import android.widget.CompoundButton; 7 import android.widget.Toast; 8 9 public class MainActivity extends ActionBarActivity { 10 11 private CheckBox cbFootBall; 12 private CheckBox cbBasketBall; 13 14 @Override 15 protected void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.activity_main); 18 19 cbFootBall = (CheckBox) super.findViewById(R.id.football); 20 cbBasketBall = (CheckBox) super.findViewById(R.id.basketball); 21 22 //给cbFootBall注册OnCheckedChangeListener事件 23 cbFootBall.setOnCheckedChangeListener(new BootBallOnCheckedChangeListener()); 24 // 给cbBasketBall注册OnCheckedChangeListener事件 25 cbBasketBall.setOnCheckedChangeListener(new BasketBallOnCheckedChangeListener()); 26 } 27 28 private class BootBallOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener { 29 30 public void onCheckedChanged(CompoundButton button, boolean isChecked) { 31 String str = ""; 32 if (isChecked) { 33 cbBasketBall.setChecked(false); // 设置cbBasketBall的选中状态为false 34 str = cbFootBall.getText().toString(); 35 Toast.makeText(getApplicationContext(), "您的爱好是:" + str,0).show(); 36 } 37 } 38 } 39 40 private class BasketBallOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener { 41 42 public void onCheckedChanged(CompoundButton button, boolean isChecked) { 43 String str = ""; 44 if (cbBasketBall.isChecked()) { 45 cbFootBall.setChecked(false); // 设置cbFootBall的选中状态为false 46 str = cbBasketBall.getText().toString(); 47 Toast.makeText(getApplicationContext(), "您的爱好是:" + str, 0).show(); 48 } 49 } 50 } 51 }