xml布局文件如下:
<RadioGroup
android:/>
MainActivity.java的OnCreate方法中相应的代码如下:
genderGroup = (RadioGroup)findViewById(R.id.sex);
femaleButton = (RadioButton)findViewById(R.id.female);
maleButton = (RadioButton)findViewById(R.id.male);
genderGroup.setOnCheckedChangeListener(new GenderGroupListener());
swimBox = (CheckBox)findViewById(R.id.swim);
footBallBox = (CheckBox)findViewById(R.id.football);
swimBox.setOnCheckedChangeListener(new HobbykBoxListener());
footBallBox.setOnCheckedChangeListener(new HobbykBoxListener());
定义genderGroup、CheckBox的监听器,注意二者的监听器的参数不同:
class GenderGroupListener implements OnCheckedChangeListener{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
//group点击的组的对象,checkedId组中的RadioButton对象的ID
if(femaleButton.getId() == checkedId){
Toast.makeText(MainActivity.this, "女", Toast.LENGTH_SHORT).show();
}
else if(maleButton.getId() == checkedId){
Toast.makeText(MainActivity.this, "男", Toast.LENGTH_SHORT).show();
}
}
}
class HobbykBoxListener implements android.widget.CompoundButton.OnCheckedChangeListener{
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
// TODO Auto-generated method stub
//isChecked是否选中,如果选中则传入真,否则传入假
if(isChecked){
Toast.makeText(MainActivity.this, buttonView.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
}