参考以下核心代码:@Entry @Component struct DouYin { controller: SwiperController = new SwiperController() @State videoList: VideoItem[] = allData @State currentIndex: number = 0 build() { Swiper(this.controller) { ForEach(this.videoList, (item: VideoItem, index: number) => { PlayVideo({ item, index, currentIndex: this.currentIndex }) }) } .height('100%') .width('100%') .vertical(true) .indicator(false) .cachedCount(3) .loop(false) .duration(200) .curve(Curve.EaseOut) .onChange((index: number) => { this.currentIndex = index }) } } @Component struct PlayVideo { item: Partial<VideoItem> = {} index: number = -1 @Prop currentIndex: number @State playIng: boolean = false controller: VideoController = new VideoController() prepared: boolean = false build() { Stack({ alignContent: Alignment.Bottom }) { Stack() { if (this.index === this.currentIndex) { Video({ src: this.item.videoUrl, controller: this.controller }) .width('100%') .aspectRatio(1.4) .controls(false) .onPrepared(() => { this.playIng = true this.controller.start() }) .objectFit(ImageFit.Contain) .onClick(() => { this.playIng = false this.controller.pause() }) } Image(this.item.imgUrl) .width(this.index === this.currentIndex ? 0 : '100%') .aspectRatio(1.4) .animation({ duration: 300 }) if (!this.playIng) { Row() { Image($r('app.media.ic_public_play')) .width(100) .height(100) .fillColor("#9d9393") }.width('100%') .justifyContent(FlexAlign.Center) .onClick(() => { this.controller.start() this.playIng = true }) } } .backgroundColor(Color.Black) .height('100%') .width('100%') Text(this.item.title) .fontColor(Color.White) .width('100%') .padding(20) .fontSize(20) .height(150) .lineHeight(28) .fontWeight(FontWeight.Bold) .textOverflow({ overflow: TextOverflow.Ellipsis }) } .height('100%') } } class VideoItem { videoUrl: string = '' imgUrl: ResourceStr = '' title: string = "" } const allData: VideoItem[] = [ { imgUrl: $r('app.media.back'), videoUrl: '视频资源', title: '标题' }, { imgUrl: $r('app.media.back'), videoUrl: '视频资源', title: '标题', }, ]
参考以下核心代码: