Handling Radio Button Events
In HarmonyOS ArkTS, the Radio component allows users to select one option from a group. Each radio button must share the same group value to ensure mutual exclusivity. Event handling is done via the .onChange() modifier.
// Example: Basic Radio Group with Logging
import router from '@ohos.router';
@Entry
@Component
struct Index {
build() {
Row() {
Radio({ value: 'optionA', group: 'modeGroup' })
.onChange((selected: boolean) => {
if (selected) {
console.log('Option A selected');
}
})
Radio({ value: 'optionB', group: 'modeGroup' })
.onChange((selected: boolean) => {
if (selected) {
console.log('Option B selected');
}
})
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
.padding({ top: 5 })
}
}
Practical Use Cases
Radio buttons are ideal for scenarios requiring single-selection among mutually exclusive options:
- User preferences: Language, theme, or notification settings.
- Filtering: Selecting a single category or price range in e-commerce apps.
- Payment methods: Choosing between credit card, digital wallet, or bank transfer.
- Profile forms: Gender or role selection during registration.
- Multi-step workflows: Picking a action path in guided procseses.
Complete Example: Notification Mode Selector
The following code demonstrates a UI for selecting device notification modes using styled radio buttons with visual feedback via toast messages.
// Example: Notification Mode Selector
import promptAction from '@ohos.promptAction';
@Entry
@Component
struct NotificationModeSelector {
build() {
Row() {
Column() {
Radio({ value: 'ring', group: 'notifyGroup' })
.checked(true)
.width(50)
.height(50)
.onChange((isActive) => {
if (isActive) {
promptAction.showToast({ message: 'Ringing mode activated.' });
}
})
Text('Ringing')
}
Column() {
Radio({ value: 'vibrate', group: 'notifyGroup' })
.width(50)
.height(50)
.onChange((isActive) => {
if (isActive) {
promptAction.showToast({ message: 'Vibration mode activated.' });
}
})
Text('Vibration')
}
Column() {
Radio({ value: 'silent', group: 'notifyGroup' })
.width(50)
.height(50)
.onChange((isActive) => {
if (isActive) {
promptAction.showToast({ message: 'Silent mode activated.' });
}
})
Text('Silent')
}
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}