一:RadioButton
RadioButton为单选按钮,需要和RadioGroup组合使用主要目的:获取用户选择的按钮的值
1.获取RadioGroup控件
radioGroup = (RadioGroup)findViewById(R.id.radiogroup1);2.为radioGroup添加监听事件
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
//第二个参数i为被选取的RadioButton 资源ID
// ID已可以这样获取 int id = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton)findViewById(i);
tv.setText(radioButton.getText());
}
});
1)方法getCheckedRadioButtonId()
获取选中RadioButton的ID2)onCheckedChanged()第二个参数是返回被选取RadioButton的资源ID
二:复选框CheckBox
CheckBox和RadioButton不同(一次只能选取一项),复选框一次可以复选多个目的:要对每一个checkBox做出监听,获取选中和取消的状态
//复选框的资源ID数组
int[] check_id = {R.id.box1, R.id.box2, R.id.box3, R.id.box4};
for(int id:check_id){
CheckBox chk = (CheckBox)findViewById(id);
chk.setOnCheckedChangeListener(checklistener);//对每一个checkBox注册监听对象
}
}
ArrayList<CompoundButton> selected = new ArrayList<>(); //存放被选中的checkbox组件
private CompoundButton.OnCheckedChangeListener checklistener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//参数compoundButton 为被选中的checkbox
//参数b 是isChecked是否被选中
//tvbox.setText("你选中了"+compoundButton.getText().toString());输出单个选中项
String msg = "";
if(b){
selected.add(compoundButton); //若选中则添加到集合
for(CompoundButton chk:selected)
msg += "\n"+chk.getText().toString();
tvbox.setText("你选中了"+msg);
}else{
selected.remove(compoundButton);//若取消则移除集合
tvbox.setText("你取消了"+compoundButton.getText().toString());
}
}
};
onCheckedChanged()方法第一个参数是被触发的checkBox,第二个是触发的状态