HarmonyOS鸿蒙Next中Swiper懒加载时Radio组件的选中问题
HarmonyOS鸿蒙Next中Swiper懒加载时Radio组件的选中问题 当我给Swiper组件设置成懒加载时,其内部的Radio组件就会出现无法显示为选中的问题,代码如下:
class MyDataSource implements IDataSource {
private list: number[] = []
constructor(list: number[]) {
this.list = list
}
totalCount(): number {
return this.list.length
}
getData(index: number): number {
return this.list[index]
}
registerDataChangeListener(listener: DataChangeListener): void {
}
unregisterDataChangeListener() {
}
}
@Entry
@Component
struct Index {
private swiperController: SwiperController = new SwiperController()
private data: MyDataSource = new MyDataSource([])
private theIndex: number = 0
aboutToAppear(): void {
let list: number[] = []
for (let i = 1; i <= 15; i++) {
list.push(i);
}
this.data = new MyDataSource(list)
}
build() {
Column({ space: 5 }) {
Swiper(this.swiperController) {
LazyForEach(this.data, (item: number, index: number) => {
Row() {
Radio({ value: item.toString(), group: '123'})
.checked(item === index + 1)
.hitTestBehavior(HitTestMode.None)
Text(`数组项:${item.toString()} 序号:${index + 1}`)
.width('60%')
.height(160)
.backgroundColor(0xAFEEEE)
.textAlign(TextAlign.Center)
.fontSize(30)
}.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.Center)
}, (item: string) => item)
}.width('100%')
.onChange((index) => {
this.theIndex = index
})
.cachedCount(2)
.index(5)
.autoPlay(true)
.interval(4000)
.loop(true)
.duration(1000)
.itemSpace(0)
.indicator( // 设置圆点导航点样式
new DotIndicator()
.itemWidth(8)
.itemHeight(8)
.selectedItemWidth(16)
.selectedItemHeight(8)
.color(Color.Gray)
.selectedColor(Color.Blue)
.maxDisplayCount(9))
.displayArrow({ // 设置导航点箭头样式
showBackground: true,
isSidebarMiddle: true,
backgroundSize: 24,
backgroundColor: Color.White,
arrowSize: 18,
arrowColor: Color.Blue
}, false)
.curve(Curve.Linear)
Row({ space: 12 }) {
Button('showNext')
.onClick(() => {
this.swiperController.showNext()
})
Button('showPrevious')
.onClick(() => {
this.swiperController.showPrevious()
})
}.margin(5)
}.width('100%')
.margin({ top: 5 })
}
}
更多关于HarmonyOS鸿蒙Next中Swiper懒加载时Radio组件的选中问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
在HarmonyOS鸿蒙Next中,Swiper组件实现懒加载时,Radio组件的选中状态可能会因视图复用而出现问题。解决方案包括:
- 使用
@State
或@Link
绑定Radio的选中状态,确保状态与数据源同步; - 在
onPageChange
回调中更新选中状态; - 为每个Radio设置唯一
id
,避免复用导致的混淆。
通过这些方法,可以确保懒加载时Radio组件的选中状态正确。