一 概述
二 创建Checkbox XML中创建 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <?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:orientation="vertical"> <Checkbox ohos:id="$+id:check_box" ohos:height="match_content" ohos:width="match_content" ohos:text="This is a checkbox" ohos:check_element="$graphic:background_checkbox_check" ohos:text_size="20fp"/> </DirectionalLayout>
效果图
三 设置Checkbox 3.1 在xml中设置Checkbox的背景 layout目录下xml文件的代码 1 2 3 <Checkbox ... ohos:check_element="$graphic:background_checkbox_check" />
background_checkbox_check.xml
1 2 3 4 5 6 <?xml version="1.0" encoding="UTF-8" ?> <shape xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:shape="oval"> <solid ohos:color="#00FFCC"/> </shape>
效果图
3.2 使用Java代码设置Checkbox在选中与取消选中时的背景 Java代码设置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ShapeElement elementButtonOn = new ShapeElement(); elementButtonOn.setRgbColor(RgbPalette.RED); elementButtonOn.setShape(ShapeElement.RECTANGLE); elementButtonOn.setCornerRadius(0.0f); ShapeElement elementButtonOff = new ShapeElement(); elementButtonOff.setRgbColor(RgbPalette.BLACK); elementButtonOff.setShape(ShapeElement.RECTANGLE); elementButtonOff.setCornerRadius(0.0f); StateElement checkElement = new StateElement(); checkElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, elementButtonOn); checkElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, elementButtonOff); Checkbox checkbox = (Checkbox) findComponentById(ResourceTable.Id_check_box); checkbox.setButtonElement(checkElement);
Java代码设置Checkbox背景的效果
3.3 设置Checkbox的文字在选中和取消选中时的颜色 XML中设置 1 2 3 4 <Checkbox ... ohos:text_color_on="#00AAEE" ohos:text_color_off="#000000" />
设置Checkbox文字颜色的效果
3.4 设置Checkbox的选中状态 1 checkbox.setChecked(true);
3.5 设置不同状态之间的切换 如果当前为选中状态,那么将变为未选中;
如果当前是未选中状态,将变为选中状态
3.6 设置响应Checkbox状态变更的事件 1 2 3 4 5 6 checkbox.setCheckedStateChangedListener(new AbsButton.CheckedStateChangedListener() { @Override public void onCheckedChanged(AbsButton absButton, boolean b) { new ToastDialog(getContext()).setText("是否选中:"+b).show(); } });