“请选择你喜欢的网站?A、ATAAW.COM B、Google.com C、Android.com”,没错,当我们在软件实现以上内容供用户选项,当然要使用的是复选项控件,那么在Android的界面开发中我们使用哪个控件呢?答案就是Android的复选框CheckBox了。那么,具体如何实现呢,ATAAW.COM来稍做介绍。
既然是复选框,当然具备选中跟未选中状态,我们可以根据控件是否被选中来进行相应的操作,通过对复选框加载时间监听器,来对控件状态的改变作出Actions,当然也可以只对控件是否被选中做判断即可,而在其他控件的监听处理中执行其他操作,这个就根据具体的业务需求来选择。
我们先在布局文件中声明创建3个复选框控件,分别称为“WWW”,“ATAAW”,“COM”。
1 2 3 4 5 6 | <CheckBox android:text="WWW" android:id="@+id/ataaw1" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox> <CheckBox android:text="ATAAW" android:id="@+id/ataaw2" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox> <CheckBox android:text="COM" android:id="@+id/ataaw3" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox> |
为以上复选框添加时间监听器,为了方便起见,我们这里为三个复选框添加同一个时间监听器,通过判断其响应的ID确定哪一个复选框被选中。
A、首先定义监听器
1 2 3 4 5 6 7 8 9 10 11 12 13 | OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { switch(buttonView.getId()){ case R.id.ataaw1: //action break; case R.id.ataaw2: //action break; case R.id.ataaw3: //action break; } } } |
B、指定监听器
1 2 3 4 5 6 | CheckBox www = (CheckBox) this.findViewById(R.id.ataaw1); CheckBox ataaw = (CheckBox) this.findViewById(R.id.ataaw2); CheckBox com = (CheckBox) this.findViewById(R.id.ataaw3); www.setOnCheckedChangeListener(listener); ataaw.setOnCheckedChangeListener(listener); com.setOnCheckedChangeListener(listener); |
以上即是Android开发中复选框的基本使用方法。
原文作者:diordna