• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Checkbox
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @houguobiao-->
5<!--Designer: @houguobiao-->
6<!--Tester: @lxl007-->
7<!--Adviser: @HelloCrease-->
8
9提供多选框组件,通常用于某选项的打开或关闭。
10
11>  **说明:**
12>
13>  API version 11开始,Checkbox默认样式由圆角方形变为圆形。
14>
15>  该组件从API version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
16
17## 子组件
18
1920
21## 接口
22
23Checkbox(options?: CheckboxOptions)
24
25多选框组件。
26
27**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
28
29**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
30
31**系统能力:** SystemCapability.ArkUI.ArkUI.Full
32
33**参数:**
34
35| 参数名  | 类型                                        | 必填 | 说明               |
36| ------- | ------------------------------------------- | ---- | ------------------ |
37| options | [CheckboxOptions](#checkboxoptions对象说明) | 否   | 配置多选框的参数。 |
38
39## CheckboxOptions对象说明
40
41多选框的信息。
42
43**系统能力:** SystemCapability.ArkUI.ArkUI.Full
44
45| 名称  | 类型 | 只读 | 可选 | 说明 |
46| --------| --------| ------ | -------- | -------- |
47| name    | string | 否 | 是 | 指定多选框名称。 <br/>**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
48| group   | string | 否 | 是 | 用于指定多选框所属群组的名称(即所属CheckboxGroup的名称)。<br/>**说明:** <br/>未配合使用[CheckboxGroup](ts-basic-components-checkboxgroup.md)组件时,此值无用。 <br/>**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
49| indicatorBuilder<sup>12+</sup> | [CustomBuilder](ts-types.md#custombuilder8) | 否 | 是 | 配置多选框的选中样式为自定义组件。自定义组件与Checkbox组件为中心点对齐显示。indicatorBuilder设置为undefined/null时,默认为indicatorBuilder未设置状态。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
50
51## 属性
52
53除支持[通用属性](ts-component-general-attributes.md)外,还支持以下属性:
54
55### select
56
57select(value: boolean)
58
59设置多选框选中状态。
60
61从API version 10开始,该属性支持[$$](../../../ui/state-management/arkts-two-way-sync.md)双向绑定变量。
62
63从API version 18开始,该属性支持[!!](../../../ui/state-management/arkts-new-binding.md#系统组件参数双向绑定)双向绑定变量。
64
65**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
66
67**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
68
69**系统能力:** SystemCapability.ArkUI.ArkUI.Full
70
71**参数:**
72
73| 参数名 | 类型    | 必填 | 说明                                                         |
74| ------ | ------- | ---- | ------------------------------------------------------------ |
75| value  | boolean | 是   | 多选框是否选中。<br/>默认值:false<br/>值为true时,多选框被选中。值为false时,多选框未选中。 |
76
77### select<sup>18+</sup>
78
79select(isSelected: Optional\<boolean>)
80
81设置多选框选中状态。与[select](#select)相比,isSelected参数新增了对undefined类型的支持。
82
83该属性支持[$$](../../../ui/state-management/arkts-two-way-sync.md)、[!!](../../../ui/state-management/arkts-new-binding.md#系统组件参数双向绑定)双向绑定变量。
84
85**卡片能力:** 从API version 18开始,该接口支持在ArkTS卡片中使用。
86
87**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
88
89**系统能力:** SystemCapability.ArkUI.ArkUI.Full
90
91**参数:**
92
93| 参数名     | 类型                                                         | 必填 | 说明                                                         |
94| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
95| isSelected | [Optional](ts-universal-attributes-custom-property.md#optionalt12)\<boolean> | 是   | 多选框是否选中。<br/>当isSelected的值为undefined时取默认值false。<br/>值为true时,多选框被选中。值为false时,多选框未选中。 |
96
97### selectedColor
98
99selectedColor(value: ResourceColor)
100
101设置多选框选中状态颜色。
102
103**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
104
105**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
106
107**系统能力:** SystemCapability.ArkUI.ArkUI.Full
108
109**参数:**
110
111| 参数名 | 类型                                       | 必填 | 说明                                                         |
112| ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ |
113| value  | [ResourceColor](ts-types.md#resourcecolor) | 是   | 多选框选中状态颜色。<br/>默认值:$r('sys.color.ohos_id_color_text_primary_activated')<br/>异常值按照默认值处理。 |
114
115### selectedColor<sup>18+</sup>
116
117selectedColor(resColor: Optional\<ResourceColor>)
118
119设置多选框选中状态颜色。与[selectedColor](#selectedcolor)相比,resColor参数新增了对undefined类型的支持。
120
121**卡片能力:** 从API version 18开始,该接口支持在ArkTS卡片中使用。
122
123**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
124
125**系统能力:** SystemCapability.ArkUI.ArkUI.Full
126
127**参数:**
128
129| 参数名   | 类型                                                         | 必填 | 说明                                                         |
130| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
131| resColor | [Optional](ts-universal-attributes-custom-property.md#optionalt12)\<[ResourceColor](ts-types.md#resourcecolor)> | 是   | 多选框选中状态颜色。<br/>当resColor的值为undefined时取默认值$r('sys.color.ohos_id_color_text_primary_activated')。<br/>异常值按照默认值处理。 |
132
133### unselectedColor<sup>10+</sup>
134
135unselectedColor(value: ResourceColor)
136
137设置多选框非选中状态的边框颜色。
138
139**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
140
141**系统能力:** SystemCapability.ArkUI.ArkUI.Full
142
143**参数:**
144
145| 参数名 | 类型                                       | 必填 | 说明                     |
146| ------ | ------------------------------------------ | ---- | -------------------------- |
147| value  | [ResourceColor](ts-types.md#resourcecolor) | 是   | 多选框非选中状态边框颜色。<br/>默认值:$r('sys.color.ohos_id_color_switch_outline_off') |
148
149### unselectedColor<sup>18+</sup>
150
151unselectedColor(resColor: Optional\<ResourceColor>)
152
153设置多选框非选中状态的边框颜色。与[unselectedColor](#unselectedcolor10)<sup>10+</sup>相比,resColor参数新增了对undefined类型的支持。
154
155**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
156
157**系统能力:** SystemCapability.ArkUI.ArkUI.Full
158
159**参数:**
160
161| 参数名   | 类型                                                         | 必填 | 说明                                                         |
162| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
163| resColor | [Optional](ts-universal-attributes-custom-property.md#optionalt12)\<[ResourceColor](ts-types.md#resourcecolor)> | 是   | 多选框非选中状态边框颜色。<br/>当resColor的值为undefined时取默认值$r('sys.color.ohos_id_color_switch_outline_off')|
164
165### mark<sup>10+</sup>
166
167mark(value: MarkStyle)
168
169设置多选框内部图标的样式。
170
171**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
172
173**系统能力:** SystemCapability.ArkUI.ArkUI.Full
174
175**参数:**
176
177| 参数名 | 类型                                         | 必填 | 说明                                                         |
178| ------ | -------------------------------------------- | ---- | ------------------------------------------------------------ |
179| value  | [MarkStyle](ts-types.md#markstyle10对象说明) | 是   | 多选框内部图标样式。 从API version 12开始,设置了indicatorBuilder时,按照indicatorBuilder中的内容显示。<br/>默认值:{<br/>strokeColor : `$r('sys.color.ohos_id_color_foreground_contrary')`,<br/>strokeWidth: `$r('sys.float.ohos_id_checkbox_stroke_width')`,<br/>size: '20vp'<br/>} |
180
181### mark<sup>18+</sup>
182
183mark(style: Optional\<MarkStyle>)
184
185设置多选框内部图标的样式。与[mark](#mark10)<sup>10+</sup>相比,style参数新增了对undefined类型的支持。
186
187**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
188
189**系统能力:** SystemCapability.ArkUI.ArkUI.Full
190
191**参数:**
192
193| 参数名 | 类型                                                         | 必填 | 说明                                                         |
194| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
195| style  | [Optional](ts-universal-attributes-custom-property.md#optionalt12)\<[MarkStyle](ts-types.md#markstyle10对象说明)> | 是   | 多选框内部图标样式。 设置了indicatorBuilder时,按照indicatorBuilder中的内容显示。<br/>当style的值为undefined时,默认值:{<br/>strokeColor : `$r('sys.color.ohos_id_color_foreground_contrary')`,<br/>strokeWidth: `$r('sys.float.ohos_id_checkbox_stroke_width')`,<br/>size: '20vp'<br/>} |
196
197### shape<sup>11+</sup>
198
199shape(value: CheckBoxShape)
200
201设置CheckBox组件形状,包括圆形和圆角方形。如果想要调整当前CheckBox的样式,需使用[contentModifier](#contentmodifier12)属性自定义CheckBox样式。
202
203**卡片能力:** 从API version 11开始,该接口支持在ArkTS卡片中使用。
204
205**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
206
207**系统能力:** SystemCapability.ArkUI.ArkUI.Full
208
209**参数:**
210
211| 参数名 | 类型                                                  | 必填 | 说明                                                         |
212| ------ | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
213| value  | [CheckBoxShape](ts-appendix-enums.md#checkboxshape11) | 是   | CheckBox组件形状,包括圆形和圆角方形。<br/>默认值:CheckBoxShape.CIRCLE |
214
215### shape<sup>18+</sup>
216
217shape(shape: Optional\<CheckBoxShape>)
218
219设置CheckBox组件形状,包括圆形和圆角方形。与[shape](#shape11)<sup>11+</sup>相比,shape参数新增了对undefined类型的支持。如果想要调整当前CheckBox的样式,需使用[contentModifier](#contentmodifier12)属性自定义CheckBox样式。
220
221**卡片能力:** 从API version 18开始,该接口支持在ArkTS卡片中使用。
222
223**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
224
225**系统能力:** SystemCapability.ArkUI.ArkUI.Full
226
227**参数:**
228
229| 参数名 | 类型                                                         | 必填 | 说明                                                         |
230| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
231| shape  | [Optional](ts-universal-attributes-custom-property.md#optionalt12)\<[CheckBoxShape](ts-appendix-enums.md#checkboxshape11)> | 是   | CheckBox组件形状,包括圆形和圆角方形。<br/>当shape的值为undefined时,默认值为CheckBoxShape.CIRCLE。 |
232
233### contentModifier<sup>12+</sup>
234
235contentModifier(modifier: ContentModifier\<CheckBoxConfiguration>)
236
237定制CheckBox内容区的方法。设置该属性时,会导致其他属性设置失效。
238
239**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
240
241**系统能力:** SystemCapability.ArkUI.ArkUI.Full
242
243**参数:**
244
245| 参数名 | 类型                                          | 必填 | 说明                                             |
246| ------ | --------------------------------------------- | ---- | ------------------------------------------------ |
247| modifier  | [ContentModifier\<CheckBoxConfiguration>](#checkboxconfiguration12对象说明) | 是   | 在CheckBox组件上,定制内容区的方法。<br/>modifier:内容修改器,开发者需要自定义class实现ContentModifier接口。 |
248
249### contentModifier<sup>18+</sup>
250
251contentModifier(modifier: Optional<ContentModifier\<CheckBoxConfiguration>>)
252
253定制CheckBox内容区的方法。与[contentModifier](#contentmodifier12)<sup>12+</sup>相比,modifier参数新增了对undefined类型的支持。设置该属性时,会导致其他属性设置失效。
254
255**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
256
257**系统能力:** SystemCapability.ArkUI.ArkUI.Full
258
259**参数:**
260
261| 参数名   | 类型                                                         | 必填 | 说明                                                         |
262| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
263| modifier | [Optional](ts-universal-attributes-custom-property.md#optionalt12)\<[ContentModifier\<CheckBoxConfiguration>](#checkboxconfiguration12对象说明)> | 是   | 在CheckBox组件上,定制内容区的方法。<br/>modifier:内容修改器,开发者需要自定义class实现ContentModifier接口。<br/>当modifier的值为undefined时,不使用内容修改器。 |
264
265## 事件
266
267支持[通用事件](ts-component-general-events.md)外,还支持以下事件:
268
269### onChange
270
271onChange(callback: OnCheckboxChangeCallback)
272
273当选中状态发生变化时,触发该回调。
274
275**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
276
277**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
278
279**系统能力:** SystemCapability.ArkUI.ArkUI.Full
280
281**参数:**
282
283| 参数名   | 类型                                                    | 必填 | 说明             |
284| -------- | ------------------------------------------------------- | ---- | ---------------- |
285| callback | [OnCheckboxChangeCallback](#oncheckboxchangecallback18) | 是   | 返回选中的状态。 |
286
287### onChange<sup>18+</sup>
288
289onChange(callback: Optional\<OnCheckboxChangeCallback>)
290
291当选中状态发生变化时,触发该回调。与[onChange](#onchange)相比,callback参数新增了对undefined类型的支持。
292
293**卡片能力:** 从API version 18开始,该接口支持在ArkTS卡片中使用。
294
295**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
296
297**系统能力:** SystemCapability.ArkUI.ArkUI.Full
298
299**参数:**
300
301| 参数名   | 类型                                                         | 必填 | 说明                                                         |
302| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
303| callback | [Optional](ts-universal-attributes-custom-property.md#optionalt12)\<[OnCheckboxChangeCallback](#oncheckboxchangecallback18)> | 是   | 返回选中的状态。<br/>当callback的值为undefined时,不使用回调函数。 |
304
305## OnCheckboxChangeCallback<sup>18+</sup>
306
307type OnCheckboxChangeCallback  = (value: boolean) => void
308
309选中的状态。
310
311**卡片能力:** 从API version 18开始,该接口支持在ArkTS卡片中使用。
312
313**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
314
315**系统能力:** SystemCapability.ArkUI.ArkUI.Full
316
317**参数:**
318
319| 参数名 | 类型    | 必填 | 说明                                              |
320| ------ | ------- | ---- | ------------------------------------------------- |
321| value  | boolean | 是   | 返回true表示已选中。返回false表示未选中。 |
322
323## CheckBoxConfiguration<sup>12+</sup>对象说明
324
325开发者需要自定义class实现ContentModifier接口。继承自[CommonConfiguration](ts-universal-attributes-content-modifier.md#commonconfigurationt)。
326
327**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
328
329**系统能力:** SystemCapability.ArkUI.ArkUI.Full
330
331| 名称 | 类型    |    只读    |    可选      |  说明              |
332| ------ | ------ | ------ |-------------------------------- |-------------------------------- |
333| name | string | 否 | 否 |当前多选框名称。 |
334| selected | boolean| 否 | 否 | 指示多选框是否被选中,值为true时,多选框被选中。值为false时,多选框未选中。</br>如果select属性没有设置默认值是false。</br>如果设置select属性,此值与设置select属性的值相同。 |
335| triggerChange |Callback\<boolean>| 否 | 否 |触发多选框选中状态变化。true表示从未选中变为选中,false表示从选中变为未选中。 |
336
337## 示例
338
339### 示例1(设置多选框形状)
340
341该示例通过配置CheckBoxShape实现圆形和圆角方形多选框样式。
342
343```ts
344// xxx.ets
345@Entry
346@Component
347struct CheckboxExample {
348  build() {
349    Flex({ justifyContent: FlexAlign.SpaceEvenly }) {
350      Checkbox({ name: 'checkbox1', group: 'checkboxGroup' })
351        .select(true)
352        .selectedColor(0xed6f21)
353        .shape(CheckBoxShape.CIRCLE)
354        .onChange((value: boolean) => {
355          console.info('Checkbox1 change is' + value);
356        })
357      Checkbox({ name: 'checkbox2', group: 'checkboxGroup' })
358        .select(false)
359        .selectedColor(0x39a2db)
360        .shape(CheckBoxShape.ROUNDED_SQUARE)
361        .onChange((value: boolean) => {
362          console.info('Checkbox2 change is' + value);
363        })
364    }
365  }
366}
367```
368
369
370![](figures/checkbox.gif)
371
372### 示例2(设置多选框颜色)
373
374该示例通过配置mark实现自定义多选框的颜色。
375
376```ts
377// xxx.ets
378@Entry
379@Component
380struct Index {
381
382  build() {
383    Row() {
384      Column() {
385        Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
386          Checkbox({ name: 'checkbox1', group: 'checkboxGroup' })
387            .selectedColor(0x39a2db)
388            .shape(CheckBoxShape.ROUNDED_SQUARE)
389            .onChange((value: boolean) => {
390              console.info('Checkbox1 change is'+ value);
391            })
392            .mark({
393              strokeColor:Color.Black,
394              size: 50,
395              strokeWidth: 5
396            })
397            .unselectedColor(Color.Red)
398            .width(30)
399            .height(30)
400          Text('Checkbox1').fontSize(20)
401        }
402        Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
403          Checkbox({ name: 'checkbox2', group: 'checkboxGroup' })
404            .selectedColor(0x39a2db)
405            .shape(CheckBoxShape.ROUNDED_SQUARE)
406            .onChange((value: boolean) => {
407              console.info('Checkbox2 change is' + value);
408            })
409            .width(30)
410            .height(30)
411          Text('Checkbox2').fontSize(20)
412        }
413      }
414      .width('100%')
415    }
416    .height('100%')
417  }
418}
419```
420
421
422![](figures/checkbox2.gif)
423
424### 示例3(自定义多选框样式)
425该示例通过[contentModifier](#contentmodifier12)属性实现了自定义复选框样式的功能,自定义样式实现了一个五边形复选框,如果选中,内部会出现红色三角图案,标题会显示选中字样,如果取消选中,红色三角图案消失,标题会显示非选中字样。
426
427```ts
428// xxx.ets
429class MyCheckboxStyle implements ContentModifier<CheckBoxConfiguration> {
430  selectedColor: Color = Color.White;
431
432  constructor(selectedColor: Color) {
433    this.selectedColor = selectedColor;
434  }
435
436  applyContent(): WrappedBuilder<[CheckBoxConfiguration]> {
437    return wrapBuilder(buildCheckbox);
438  }
439}
440
441@Builder
442function buildCheckbox(config: CheckBoxConfiguration) {
443  Column({ space: 10 }) {
444    Text(config.name + (config.selected ? "( 选中 )" : "( 非选中 )")).margin({ right: 70, top: 50 })
445    Text(config.enabled ? "enabled true" : "enabled false").margin({ right: 110 })
446    Shape() {
447      Path()
448        .width(100)
449        .height(100)
450        .commands('M100 0 L0 100 L50 200 L150 200 L200 100 Z')
451        .fillOpacity(0)
452        .strokeWidth(3)
453        .onClick(() => {
454          if (config.selected) {
455            config.triggerChange(false);
456          } else {
457            config.triggerChange(true);
458          }
459        })
460        .opacity(config.enabled ? 1 : 0.1)
461      Path()
462        .width(10)
463        .height(10)
464        .commands('M50 0 L100 100 L0 100 Z')
465        .visibility(config.selected ? Visibility.Visible : Visibility.Hidden)
466        .fill(config.selected ? (config.contentModifier as MyCheckboxStyle).selectedColor : Color.Black)
467        .stroke((config.contentModifier as MyCheckboxStyle).selectedColor)
468        .margin({ left: 10, top: 10 })
469        .opacity(config.enabled ? 1 : 0.1)
470    }
471    .width(300)
472    .height(200)
473    .viewPort({
474      x: 0,
475      y: 0,
476      width: 310,
477      height: 310
478    })
479    .strokeLineJoin(LineJoinStyle.Miter)
480    .strokeMiterLimit(5)
481    .margin({ left: 50 })
482  }
483}
484
485@Entry
486@Component
487struct Index {
488  @State checkboxEnabled: boolean = true;
489
490  build() {
491    Column({ space: 100 }) {
492      Checkbox({ name: '复选框状态', group: 'checkboxGroup' })
493        .contentModifier(new MyCheckboxStyle(Color.Red))
494        .onChange((value: boolean) => {
495          console.info('Checkbox change is' + value);
496        }).enabled(this.checkboxEnabled)
497
498      Row() {
499        Toggle({ type: ToggleType.Switch, isOn: true }).onChange((value: boolean) => {
500          if (value) {
501            this.checkboxEnabled = true;
502          } else {
503            this.checkboxEnabled = false;
504          }
505        })
506      }.position({ x: 50, y: 130 })
507    }.margin({ top: 30 })
508  }
509}
510```
511
512
513![](figures/checkbox3.gif)
514
515### 示例4(设置文本多选框样式)
516该示例通过配置indicatorBuilder实现选中样式为Text。
517```ts
518// xxx.ets
519@Entry
520@Component
521struct CheckboxExample {
522  @Builder
523  indicatorBuilder(value: number) {
524    Column(){
525      Text(value > 99 ? '99+': value.toString())
526        .textAlign(TextAlign.Center)
527        .fontSize(value > 99 ?  '16vp': '20vp')
528        .fontWeight(FontWeight.Medium)
529        .fontColor('#ffffffff')
530    }
531  }
532  build() {
533    Row() {
534      Column() {
535        Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center}) {
536          Checkbox({ name: 'checkbox1', group: 'checkboxGroup', indicatorBuilder:()=>{this.indicatorBuilder(9)}})
537            .shape(CheckBoxShape.CIRCLE)
538            .onChange((value: boolean) => {
539              console.info('Checkbox1 change is'+ value);
540            })
541            .mark({
542              strokeColor:Color.Black,
543              size: 50,
544              strokeWidth: 5
545            })
546            .width(30)
547            .height(30)
548          Text('Checkbox1').fontSize(20)
549        }.padding(15)
550        Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
551          Checkbox({ name: 'checkbox2', group: 'checkboxGroup', indicatorBuilder:()=>{this.indicatorBuilder(100)}})
552            .shape(CheckBoxShape.ROUNDED_SQUARE)
553            .onChange((value: boolean) => {
554              console.info('Checkbox2 change is' + value);
555            })
556            .width(30)
557            .height(30)
558          Text('Checkbox2').fontSize(20)
559        }
560      }
561      .width('100%')
562    }
563    .height('100%')
564  }
565}
566```
567
568![](figures/checkbox4.gif)
569
570### 示例5(获取多选框选中信息)
571
572该示例通过选中Checkbox以及CheckboxGroup多选框来获取选中的信息。
573
574```ts
575// xxx.ets
576@Entry
577@Component
578struct CheckboxExample {
579  @State arrOne: Array<string> = ['1', '2', '3'];
580  @State arrTwo: Array<string> = ['1', '2', '3', '4'];
581  @State arrThree: Array<string> = ['1', '2', '3', '4', '5', '6'];
582  @State selected: boolean = false;
583  @State infoOne: string = '';
584  @State infoTwo: string = '';
585  @State infoThree: string = '';
586
587  build() {
588    Column() {
589      // 单元项全选按钮
590      Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
591        CheckboxGroup({ group: 'checkboxGroupOne' })
592          .selectAll(this.selected)
593          .checkboxShape(CheckBoxShape.ROUNDED_SQUARE)
594          .selectedColor('#007DFF')
595          .onChange((itemName: CheckboxGroupResult) => {
596            this.infoOne = "checkboxGroupOne" + JSON.stringify(itemName);
597            console.info("checkboxGroupOne" + JSON.stringify(itemName));
598          })
599        Text('checkboxGroupOne Select All').fontSize(14).lineHeight(20).fontColor('#182431').fontWeight(500)
600      }
601
602      // 选项1
603      Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
604        Column() {
605          ForEach(this.arrOne, (item: string) => {
606            Row() {
607              Checkbox({ name: 'checkbox' + item, group: 'checkboxGroupOne' })
608                .selectedColor('#007DFF')
609                .shape(CheckBoxShape.ROUNDED_SQUARE)
610                .onChange((value: boolean) => {
611                  console.info('Checkbox' + item + 'change is' + value);
612                })
613                .margin({ left: 20 })
614              Text('Checkbox' + item)
615                .fontSize(14)
616                .lineHeight(20)
617                .fontColor('#182431')
618                .fontWeight(500)
619                .margin({ left: 10 })
620            }
621          }, (item: string) => item)
622        }
623      }.margin({ bottom: 15 })
624
625      Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
626        CheckboxGroup({ group: 'checkboxGroupTwo' })
627          .selectAll(this.selected)
628          .checkboxShape(CheckBoxShape.ROUNDED_SQUARE)
629          .selectedColor('#007DFF')
630          .onChange((itemName: CheckboxGroupResult) => {
631            this.infoTwo = "checkboxGroupTwo" + JSON.stringify(itemName);
632            console.info("checkboxGroupTwo" + JSON.stringify(itemName));
633          })
634        Text('checkboxGroupTwo Select All').fontSize(14).lineHeight(20).fontColor('#182431').fontWeight(500)
635      }
636
637      // 选项2
638      Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
639        Column() {
640          ForEach(this.arrTwo, (item: string) => {
641            Row() {
642              Checkbox({ name: 'checkbox' + item, group: 'checkboxGroupTwo' })
643                .selectedColor('#007DFF')
644                .shape(CheckBoxShape.ROUNDED_SQUARE)
645                .onChange((value: boolean) => {
646                  console.info('Checkbox' + item + 'change is' + value);
647                })
648                .margin({ left: 20 })
649              Text('Checkbox' + item)
650                .fontSize(14)
651                .lineHeight(20)
652                .fontColor('#182431')
653                .fontWeight(500)
654                .margin({ left: 10 })
655            }
656          }, (item: string) => item)
657        }
658      }.margin({ bottom: 15 })
659
660      Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
661        CheckboxGroup({ group: 'checkboxGroupThree' })
662          .selectAll(this.selected)
663          .checkboxShape(CheckBoxShape.ROUNDED_SQUARE)
664          .selectedColor('#007DFF')
665          .onChange((itemName: CheckboxGroupResult) => {
666            this.infoThree = "checkboxGroupThree" + JSON.stringify(itemName);
667            console.info("checkboxGroupThree" + JSON.stringify(itemName));
668          })
669        Text('checkboxGroupThree Select All').fontSize(14).lineHeight(20).fontColor('#182431').fontWeight(500)
670      }
671
672      // 选项3
673      Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
674        Column() {
675          ForEach(this.arrThree, (item: string) => {
676            Row() {
677              Checkbox({ name: 'checkbox' + item, group: 'checkboxGroupThree' })
678                .selectedColor('#007DFF')
679                .shape(CheckBoxShape.ROUNDED_SQUARE)
680                .onChange((value: boolean) => {
681                  console.info('Checkbox' + item + 'change is' + value);
682                })
683                .margin({ left: 20 })
684              Text('Checkbox' + item)
685                .fontSize(14)
686                .lineHeight(20)
687                .fontColor('#182431')
688                .fontWeight(500)
689                .margin({ left: 10 })
690            }
691          }, (item: string) => item)
692        }
693      }.margin({ bottom: 15 })
694
695      //全选按钮
696      Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
697        Row() {
698          CheckboxGroup({ group: 'checkboxGroup' })
699            .checkboxShape(CheckBoxShape.CIRCLE)
700            .selectedColor('#007DFF')
701            .width(30)
702            .margin({ left: 10 })
703            .onChange(() => {
704              this.selected = !this.selected
705            })
706          Text('Select All')
707            .fontSize(14)
708            .lineHeight(20)
709            .fontColor('#182431')
710            .fontWeight(500)
711            .margin({ left: 10 })
712        }
713      }.margin({ bottom: 15 })
714
715      //获取选中信息
716      Button('get selected info')
717        .margin({ top: 10 })
718        .onClick(() => {
719          this.getUIContext().getPromptAction().showToast({
720            message: 'selected info: ' + this.infoOne + '\n' + this.infoTwo + '\n' + this.infoThree
721          })
722        })
723    }.padding(10)
724  }
725}
726```
727
728![checkbox5](figures/checkbox5.gif)
729
730### 示例6(设置滑动多选)
731
732该示例通过设置手势事件实现Checkbox滑动多选。
733
734```ts
735// xxx.ets
736import { componentUtils, ComponentUtils, UIContext } from '@kit.ArkUI';
737import { LinkedList } from '@kit.ArkTS';
738
739@Entry
740@Component
741struct Index {
742  @State isChoosing: boolean = false;
743  @State selectedStart: number = -1;
744  @State @Watch('onSelectedEndChange') selectedEnd: number = -1;
745  selectedPhotos: LinkedList<number> = new LinkedList();
746  @State selectedList: number[] = [];
747  @State image: Resource[] =
748    // $r('app.media.xxx')需要替换为开发者所需的图像资源文件。
749    [$r("app.media.imageOne"), $r('app.media.imageTwo'), $r('app.media.imageThree'), $r('app.media.imageFour')];
750  private selectedState: SelectedState = SelectedState.None;
751  private componentUtils: ComponentUtils = this.getUIContext().getComponentUtils();
752  private listScroller: ListScroller = new ListScroller();
753  private currentOffsetY: number = 0;
754
755  onChange() {
756    console.info('change successful');
757  }
758
759  getSpeed(fingerY: number, edge: number) {
760    return 150 * 150 * (fingerY - edge) / 2000 / Math.abs(fingerY - edge);
761  }
762
763  getIndex(fingerX: number, fingerY: number) {
764    let rect: componentUtils.ComponentInfo | null = null;
765    for (let i = 0; i < 100; i++) {
766      let uiContext: UIContext = this.getUIContext();
767      rect = this.componentUtils.getRectangleById(`stack${i}`);
768      if (rect) {
769        const x1 = uiContext.px2vp(rect.windowOffset.x);
770        const x2 = uiContext.px2vp(rect.windowOffset.x + rect.size.width);
771        const y1 = uiContext.px2vp(rect.windowOffset.y);
772        const y2 = uiContext.px2vp(rect.windowOffset.y + rect.size.height);
773        if (x1 <= fingerX && fingerX < x2 && y1 <= fingerY && fingerY < y2) {
774          return i;
775        }
776      }
777    }
778    return this.selectedEnd;
779  }
780
781  onSelectedEndChange() {
782    let start: number = -1;
783    let end: number = -1;
784    if (this.selectedEnd > this.selectedStart) {
785      start = this.selectedStart;
786      end = this.selectedEnd;
787    } else {
788      end = this.selectedStart;
789      start = this.selectedEnd;
790    }
791    if (this.selectedState == SelectedState.Selected) {
792      for (let i = start; i <= end; i++) {
793        if (!this.selectedPhotos.has(i)) {
794          this.selectedPhotos.add(i);
795        }
796      }
797    } else if (this.selectedState == SelectedState.Remove) {
798      for (let i = start; i <= end; i++) {
799        if (this.selectedPhotos.has(i)) {
800          this.selectedPhotos.remove(i);
801        }
802      }
803    }
804    this.selectedList = this.selectedPhotos.convertToArray();
805  }
806
807  scroll(fingerY: number) {
808    if (fingerY > 700 && !this.listScroller.isAtEnd()) {
809      this.listScroller.scrollBy(0, this.getSpeed(fingerY, 700));
810      return;
811    }
812    if (fingerY < 200 && this.currentOffsetY > 0) {
813      this.listScroller.scrollBy(0, this.getSpeed(fingerY, 200));
814      return;
815    }
816  }
817
818  onPanGestureUpdate(event: GestureEvent) {
819    const fingerInfo = event.fingerList[event.fingerList.length - 1];
820    const fingerX = fingerInfo.globalX;
821    const fingerY = fingerInfo.globalY;
822    this.selectedEnd = this.getIndex(fingerX, fingerY);
823    this.scroll(fingerY);
824  }
825
826  build() {
827    Column() {
828      if (this.isChoosing) {
829        Row() {
830          Text('取消')
831            .onClick(() => {
832              this.isChoosing = false;
833              this.selectedStart = -1;
834              this.selectedEnd = -1;
835              this.selectedPhotos.clear();
836              this.selectedList = [];
837            })
838        }
839        .width('100%')
840        .justifyContent(FlexAlign.SpaceEvenly)
841      }
842      List({ space: 10, scroller: this.listScroller }) {
843        ForEach(Array.from({ length: 100 }), (item: string, index: number) => {
844          ListItem() {
845            Stack({ alignContent: Alignment.TopEnd }) {
846              Image(this.image[(index % 4)])
847                .width('100%')
848                .draggable(false)
849              Checkbox({ name: index.toString() })
850                .shape(CheckBoxShape.CIRCLE)
851                .visibility(this.isChoosing ? Visibility.Visible : Visibility.None)
852                .select(this.selectedList.includes(index))
853            }
854            .id(`stack${index}`)
855            .width('100%')
856          }
857          .draggable(false)
858        }, (item: string, index: number) => 'listItem' + index)
859      }
860      .id('list')
861      .height('100%')
862      .width('100%')
863      .lanes(4)
864      .alignListItem(ListItemAlign.Center)
865      .onDidScroll(() => {
866        this.currentOffsetY = this.listScroller.currentOffset().yOffset;
867      })
868      .gesture(
869        GestureGroup(GestureMode.Exclusive,
870          GestureGroup(GestureMode.Sequence,
871            LongPressGesture()
872              .onAction(() => {
873                this.isChoosing = true;
874              }),
875            PanGesture()
876              .onActionStart(event => {
877                if (!this.isChoosing) {
878                  return;
879                }
880                const fingerInfo = event.fingerList[event.fingerList.length - 1];
881                const fingerX = fingerInfo.globalX;
882                const fingerY = fingerInfo.globalY;
883                this.selectedStart = this.getIndex(fingerX, fingerY);
884                if (this.selectedPhotos.has(this.selectedStart)) {
885                  this.selectedState = SelectedState.Remove;
886                } else {
887                  this.selectedState = SelectedState.Selected;
888                }
889              })
890              .onActionUpdate(event => {
891                if (!this.isChoosing) {
892                  return;
893                }
894                this.onPanGestureUpdate(event);
895              })
896              .onActionEnd(() => {
897                if (!this.isChoosing) {
898                  return;
899                }
900                this.selectedState = SelectedState.None;
901              })
902          ),
903          PanGesture()
904            .onActionStart(event => {
905              if (!this.isChoosing) {
906                return;
907              }
908              const fingerInfo = event.fingerList[event.fingerList.length - 1];
909              const fingerX = fingerInfo.globalX;
910              const fingerY = fingerInfo.globalY;
911              this.selectedStart = this.getIndex(fingerX, fingerY);
912              if (this.selectedPhotos.has(this.selectedStart)) {
913                this.selectedState = SelectedState.Remove;
914              } else {
915                this.selectedState = SelectedState.Selected;
916              }
917            })
918            .onActionUpdate(event => {
919              if (!this.isChoosing) {
920                return;
921              }
922              this.onPanGestureUpdate(event);
923            })
924            .onActionEnd(() => {
925              if (!this.isChoosing) {
926                return;
927              }
928              this.selectedState = SelectedState.None;
929            })
930        )
931      )
932    }
933  }
934}
935
936enum SelectedState {
937  None,
938  Selected,
939  Remove
940}
941```
942
943![checkbox6](figures/checkbox6.gif)
944