How to implement radio buttons after applying custom styles to the Radio component via ContentModifier
Problem Description
When a radio button is assigned a custom style, it transforms into a checkbox and fails to function as a single-selection option.
Background Knowledge
ContentModifier interface: Provides the ability to customize the content area of a drawing component.
Radio: A single-selection radio button providing corresponding user interaction options. contentModifier: A method for customizing the content area on the Radio component. modifier: A content modifier. Developers must implement a custom class that implements the ContentModifier interface. When the value of modifier is undefined, no content modifier is applied.
Troubleshooting Process
After adding a ContentModifier to the Radio component, selecting a radio button only updates the checked state without refreshing the displayed style.
Analysis Conclusion
Currently, when a ContentModifier is applied to the Radio component, the specification dictates that all visual effects must be implemented by the application itself.
Solution
Building upon the ContentModifier, assign a value to the checked property of each Radio using an @State binding. Assign this value within the Radio's onChange event to trigger UI updates, thereby resolving the issue.
The code example is as follows:
class DiRadio implements ContentModifier<RadioConfiguration> {
applyContent(): WrappedBuilder<[RadioConfiguration]> {
return wrapBuilder(buildDiRadio)
}
}
@Builder
function buildDiRadio(config: RadioConfiguration) {
Column() {
Image(config.checked ? $r('app.media.startIcon') : $r('app.media.background'))
.width(24).height(24)
.onClick(() => {
if (config.checked) {
config.triggerChange(false)
} else {
config.triggerChange(true)
}
})
}
}
@Entry
@Component
struct Index {
@State radio1Checked: boolean = true
@State radio2Checked: boolean = false
@State radio3Checked: boolean = false
build() {
Column() {
Column() {
Text('Radio1')
Radio({ value: 'Radio1', group: 'radioGroup' }).checked(this.radio1Checked)
.contentModifier(new DiRadio())
.onChange((isChecked: boolean) => {
this.radio1Checked = isChecked
console.info(`Radio1 status is ${isChecked}`)
})
}
Column() {
Text('Radio2')
Radio({ value: 'Radio2', group: 'radioGroup' }).checked(this.radio2Checked)
.contentModifier(new DiRadio())
.onChange((isChecked: boolean) => {
this.radio2Checked = isChecked
console.info(`Radio2 status is ${isChecked}`)
})
}
Column() {
Text('Radio3')
Radio({ value: 'Radio3', group: 'radioGroup' }).checked(this.radio3Checked)
.contentModifier(new DiRadio())
.onChange((isChecked: boolean) => {
this.radio3Checked = isChecked
console.info(`Radio3 status is ${isChecked}`)
})
}
}
.height('100%')
.width('100%')
}
}


Top comments (0)