CheckBox简介:
CheckBox和Button一样,也是一种古老的控件,它的优点在于,不用用户去填写具体的信息,只需轻轻点击,缺点在于只有“是”和“否”两种情况,但我们往往利用它的这个特性,来获取用户的一些信息。
如一个身份表单中,常常让用户填写“是否已经结婚”,显然让用户去填写“是”或“否”是不合理的,理想的情景是用如下控件:
选中后的状态:
借鉴我在Button教程中的方式,建立CheckBox的布局:
1
<
CheckBox
2
android:id
="@+id/cb"
3
android:layout_width
="wrap_content"
4
android:layout_height
="wrap_content"
5
android:checked
="false"
6
android:text
="已婚"
>
CheckBox
>
一组复选框
android:id="@+id/marketer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text=" 营销员" />
android:id="@+id/whkeeper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text=" 仓库管理员" />
显然,Checked属性是CheckBox最重要的属性之一,改变它的方式有三种:
1、XML中申明 2、代码动态改变 3、用户触摸
它的改变将会触发OnCheckedChange事件,而您可以对应的使用OnCheckedChangeListener监听器来监听这个事件。
具体的匿名监听方法代码如下:
//
获取CheckBox实例
CheckBox cb
=
(CheckBox)
this
.findViewById(R.id.cb);
//
绑定监听器
cb.setOnCheckedChangeListener(
new
OnCheckedChangeListener() { @Override
public
void
onCheckedChanged(CompoundButton arg0, boolean arg1) {
//
TODO Auto-generated method stub
Toast.makeText(MyActivity.
this
, arg1
?
"
选中了
"
:
"
取消了选中
"
, Toast.LENGTH_LONG).show(); } });
总结:
本文以最简单的例子阐述了如何在Android中使用CheckBox,并能监听它的选中状态改变事件,从而实现您需要的业务逻辑。