组件说明:
父类是AbsButton,而AbsButton的父类是Button。
当我们需要同时选择多个元素的时候就需要用到多选框组件。
比如:发送图片的时候需要多选,注册的时候选择爱好也需要多选等
常见属性:
属性名称 | 功能说明 |
---|---|
marked | 多选框的选中状态。true为选中,false为没有选中。 |
check_element | 自定义选择框的样式。样式需要跟marked的值对应。 |
常见方法:
方法名称 | 功能说明 |
---|---|
setChecked | 设置多选框的选中状态。true为选中,false为没有选中。 |
isChecked | 判断多选框的选中状态。true为选中,false为没有选中。 |
setCheckedStateChangedListener | 添加一个状态监听事件 |
本篇文章需要用到前面写的吐司弹框,记得提前加入到项目当中
ability_main.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:alignment="center"
ohos:orientation="vertical">
<Checkbox
ohos:id="$+id:cb"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="玩游戏"
ohos:text_size="30fp"
ohos:background_element="#21a8fd"/>
</DirectionalLayout>
MainAbilitySlice.java代码:
package com.example.checkboxapplication.slice;
import com.example.checkboxapplication.ResourceTable;
import com.example.checkboxapplication.toastUtils.ToastUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.AbsButton;
import ohos.agp.components.Checkbox;
import ohos.agp.components.Component;
import ohos.agp.window.dialog.ToastDialog;
public class MainAbilitySlice extends AbilitySlice implements AbsButton.CheckedStateChangedListener/*, Component.ClickedListener*/ {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
//1.找到组件
Checkbox cb = (Checkbox) findComponentById(ResourceTable.Id_cb);
//2.设置多选框选中状态
cb.setChecked(true);
//判断当前多选框是否选中
/*boolean checked = cb.isChecked();
if (checked){
ToastUtils.showDialog(this,"被选中了");
}else{
ToastUtils.showDialog(this,"没被选中");
}*/
//可以给多选框添加一个状态监听事件
//方法一:
cb.setCheckedStateChangedListener(this);
//方法二:
//cb.setClickedListener(this);
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
//当多选框状态被改变后会调用这个方法
//系统自动调用的
//参数一:多选框 参数二:状态
@Override
public void onCheckedChanged(AbsButton absButton, boolean b) {
if (b) {
ToastUtils.showDialog(this, "被选中了");
} else {
ToastUtils.showDialog(this, "没被选中");
}
}
//小结:onCheckedChanged获取点击后的状态,符合我们的逻辑
//onClick获取点击前的状态,与我们理解的状态是相反的
/* @Override
public void onClick(Component component) {
Checkbox cb = (Checkbox) component;
if(cb.isChecked()){
ToastUtils.showDialog(this, "被选中了");
}else{
ToastUtils.showDialog(this, "没被选中");
}
}*/
}
运行效果: