鴻蒙OS應用開發之——Java UI框架-常用元件Checkbox
阿新 • • 發佈:2021-01-07
一 概述
- 建立Checkbox
- 設定Checkbox
二 建立Checkbox
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: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檔案的程式碼
<Checkbox
...
ohos:check_element="$graphic:background_checkbox_check" />
background_checkbox_check.xml
<?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程式碼設定
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中設定
<Checkbox
...
ohos:text_color_on="#00AAEE"
ohos:text_color_off="#000000" />
設定Checkbox文字顏色的效果
3.4 設定Checkbox的選中狀態
checkbox.setChecked(true);
3.5 設定不同狀態之間的切換
如果當前為選中狀態,那麼將變為未選中;
如果當前是未選中狀態,將變為選中狀態
checkbox.toggle();
3.6 設定響應Checkbox狀態變更的事件
checkbox.setCheckedStateChangedListener(new AbsButton.CheckedStateChangedListener() {
@Override
public void onCheckedChanged(AbsButton absButton, boolean b) {
new ToastDialog(getContext()).setText("是否選中:"+b).show();
}
});