• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 单选框 (Radio)
2
3
4Radio是单选框组件,通常用于提供相应的用户交互选择项,同一组的Radio中只有一个可以被选中。具体用法请参考[Radio](../reference/apis-arkui/arkui-ts/ts-basic-components-radio.md)。
5
6
7## 创建单选框
8
9Radio通过调用接口来创建,接口调用形式如下:
10
11
12```ts
13Radio(options: {value: string, group: string})
14```
15
16其中,value是单选框的名称,group是单选框的所属群组名称。checked属性可以设置单选框的状态,状态分别为false和true,设置为true时表示单选框被选中。
17
18Radio支持设置选中状态和非选中状态的样式,不支持自定义形状。
19
20```ts
21Radio({ value: 'Radio1', group: 'radioGroup' })
22  .checked(false)
23Radio({ value: 'Radio2', group: 'radioGroup' })
24  .checked(true)
25```
26
27
28![zh-cn_image_0000001562820821](figures/zh-cn_image_0000001562820821.png)
29
30
31## 添加事件
32
33除支持[通用事件](../reference/apis-arkui/arkui-ts/ts-universal-events-click.md)外,Radio还用于选中后触发某些操作,可以绑定onChange事件来响应选中操作后的自定义行为。
34
35```ts
36  Radio({ value: 'Radio1', group: 'radioGroup' })
37    .onChange((isChecked: boolean) => {
38      if(isChecked) {
39        //需要执行的操作
40      }
41    })
42  Radio({ value: 'Radio2', group: 'radioGroup' })
43    .onChange((isChecked: boolean) => {
44      if(isChecked) {
45        //需要执行的操作
46      }
47    })
48```
49
50
51## 场景示例
52
53通过点击Radio切换声音模式。
54
55
56```ts
57// xxx.ets
58import promptAction from '@ohos.promptAction';
59@Entry
60@Component
61struct RadioExample {
62  @State Rst:promptAction.ShowToastOptions = {'message': 'Ringing mode.'}
63  @State Vst:promptAction.ShowToastOptions = {'message': 'Vibration mode.'}
64  @State Sst:promptAction.ShowToastOptions = {'message': 'Silent mode.'}
65  build() {
66    Row() {
67      Column() {
68        Radio({ value: 'Radio1', group: 'radioGroup' }).checked(true)
69          .height(50)
70          .width(50)
71          .onChange((isChecked: boolean) => {
72            if(isChecked) {
73              // 切换为响铃模式
74              promptAction.showToast(this.Rst)
75            }
76          })
77        Text('Ringing')
78      }
79      Column() {
80        Radio({ value: 'Radio2', group: 'radioGroup' })
81          .height(50)
82          .width(50)
83          .onChange((isChecked: boolean) => {
84            if(isChecked) {
85              // 切换为振动模式
86              promptAction.showToast(this.Vst)
87            }
88          })
89        Text('Vibration')
90      }
91      Column() {
92        Radio({ value: 'Radio3', group: 'radioGroup' })
93          .height(50)
94          .width(50)
95          .onChange((isChecked: boolean) => {
96            if(isChecked) {
97              // 切换为静音模式
98              promptAction.showToast(this.Sst)
99            }
100          })
101        Text('Silent')
102      }
103    }.height('100%').width('100%').justifyContent(FlexAlign.Center)
104  }
105}
106```
107
108
109![zh-cn_image_0000001562700457](figures/zh-cn_image_0000001562700457.png)
110