1# 单选框 (Radio) 2 3 4Radio是单选框组件,通常用于提供相应的用户交互选择项,同一组的Radio中只有一个可以被选中。具体用法请参考[Radio](../reference/apis-arkui/arkui-ts/ts-basic-components-radio.md)。 5 6 7## 创建单选框 8 9Radio通过调用[RadioOptions](../reference/apis-arkui/arkui-ts/ts-basic-components-radio.md#radiooptions对象说明)来创建,以RadioOptions中的value和group为例: 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 29 30 31## 添加事件 32 33除支持[通用事件](../reference/apis-arkui/arkui-ts/ts-component-general-events.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 '@kit.ArkUI'; 59 60@Entry 61@Component 62struct RadioExample { 63 @State Rst: promptAction.ShowToastOptions = { 'message': 'Ringing mode.' }; 64 @State Vst: promptAction.ShowToastOptions = { 'message': 'Vibration mode.' }; 65 @State Sst: promptAction.ShowToastOptions = { 'message': 'Silent mode.' }; 66 67 build() { 68 Row() { 69 Column() { 70 Radio({ value: 'Radio1', group: 'radioGroup' }).checked(true) 71 .height(50) 72 .width(50) 73 .onChange((isChecked: boolean) => { 74 if (isChecked) { 75 // 切换为响铃模式 76 this.getUIContext().getPromptAction().showToast(this.Rst); 77 } 78 }) 79 Text('Ringing') 80 } 81 82 Column() { 83 Radio({ value: 'Radio2', group: 'radioGroup' }) 84 .height(50) 85 .width(50) 86 .onChange((isChecked: boolean) => { 87 if (isChecked) { 88 // 切换为振动模式 89 this.getUIContext().getPromptAction().showToast(this.Vst); 90 } 91 }) 92 Text('Vibration') 93 } 94 95 Column() { 96 Radio({ value: 'Radio3', group: 'radioGroup' }) 97 .height(50) 98 .width(50) 99 .onChange((isChecked: boolean) => { 100 if (isChecked) { 101 // 切换为静音模式 102 this.getUIContext().getPromptAction().showToast(this.Sst); 103 } 104 }) 105 Text('Silent') 106 } 107 }.height('100%').width('100%').justifyContent(FlexAlign.Center) 108 } 109} 110``` 111 112 113 114