RadioButton和CheckBox
总结 原创
没深度解析RadioButton和CheckBox(Android)
这两天做了一个小测验应用,主要使用RadioButton和CheckBox,从最初的两眼懵逼到现在好歹了解了一些二者的基本用法,整理如下。
RadioButton
官方Guide
Radio buttons allow the user to select one option from a set. You
should use radio buttons for optional sets that are mutually exclusive
if you think that the user needs to see all available options
side-by-side. If it’s not necessary to show all options side-by-side,
use a spinner instead.
划重点:用于让用户选择互斥的选项。如果你觉得有必要让用户看到选项排成一排,那你就去用spinner。
To create each radio button option, create a RadioButton in your
layout. However, because radio buttons are mutually exclusive, you
must group them together inside a RadioGroup. By grouping them
together, the system ensures that only one radio button can be
selected at a time
划重点:因为他们是互斥的,所以你要整个RadioGroup约束他们。被约束的才能实现单选的功能。
判断是否被选中的方法:
1.isChecked()方法
将需要进行判断的RadioButton实例化,需要判断是否被选中的时候调用isChecked()方法。
2.setOnCheckedChangedListener()方法
在布局文件中将RadioButton设置在RadioGroup中,在活动中将RadioGroup 实例化,调用setOnCheckedChangedListener()并创建内部类OnCheckedChangedListener()。在监听器中写代码。
3.为RadioButton设置onClick
在布局文件中为同一组RadioButton
tips:而且RadioGroup默认orientation是vertical。
参考:android官方guideRadioButton部分
CheckBox
Checkboxes allow the user to select one or more options from a set.
Typically, you should present each checkbox option in a vertical list.
划重点:允许用户多选。一般选项都是垂直排列在一个list里的。
To create each checkbox option, create a CheckBox in your layout.
Because a set of checkbox options allows the user to select multiple
items, each checkbox is managed separately and you must register a
click listener for each one.
划重点:因为允许用户多选,所以每一个CheckBox都是独立的。你得给每一个CheckBox设置监听器。
判断是否被选中的方法:
- 将单独的CheckBox实例化
挨个检查isChecked。 - 为同组选项设置同一个onClick
然后使用switch判断哪个选项发生了CheckedChanged事件。
tips:这里之前我有一个误解,以为只有被选中才会触发CheckedChangedListener。实际上只要CheckBox的选中状态发生改变,无论是被选中还是取消选中都会触发。这个还是受了官方Guide里这段代码的启发:
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkbox_meat:
if (checked)
// Put some meat on the sandwich
else
// Remove the meat
break;
case R.id.checkbox_cheese:
if (checked)
// Cheese me
else
// I'm lactose intolerant
break;
// TODO: Veggie sandwich
}
}
这样无论选中还是取消选中都会有相应的逻辑来管,一些地方就很好处理了。
实际使用时是这样的:
checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
boolean checked = checkBox1.isChecked();
if(checked){
Toast.makeText(MainActivity.this, "11111111111", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "22222222222", Toast.LENGTH_SHORT).show();
}
}
});
参考:android官方guidecheckbox部分