自己练习顺便记录一下
先设置好界面如下
build() {
Row() {
Column() {
Swiper() {
ForEach(allData, (item: VideoItem, index: number) => {
VideoComp({
item,
index,
currentIndex: this.currentIndex
})
})
}
.vertical(true)
.index($$this.currentIndex)
.cachedCount(3)
.indicator(false)
.width('100%')
.height('100%')
}
.width('100%')
}
.height('100%')
}
里面的用到了VideoItem是一个对象数组,所以需要定义一下对象和数据
class VideoItem {
videoUrl: string = ''
title: string = ""
}
对象也可以重新创建一个文件然后导出后使用,但是小练习就没有重新创建,之后就是从VideoItem中拿出title和videoUrl地址,这里的路由自己从网上找就行
const allData: VideoItem[] = [
{
title:'标题',
videoUrl:'视频链接'
}
]
然后就是创建一个VideoComp组件
@Component
struct VideoComp {
@Require
@Prop
item: VideoItem
controller: VideoController = new VideoController()
index: number = -1
@Require
@Prop
@Watch('changPlay')
currentIndex: number
//根据index确定当前的视频播放其他视频停止
changPlay() {
this.currentIndex === this.index ? this.controller.start() : this.controller.pause()
}
@State
isPlay: boolean = true
build() {
Stack({ alignContent: Alignment.Bottom }) {
Video({
src: this.item.videoUrl,
controller: this.controller
})
.controls(false)//不展示控制条
.objectFit(ImageFit.Contain)
.autoPlay(this.index === this.currentIndex)//视频是否自动播放
//判断视频是否停止
.onClick(() => {
this.isPlay ? this.controller.pause() : this.controller.start()
})
//暂停视频
.onPause(() => {
this.isPlay = false
})
//播放视频
.onStart(() => {
this.isPlay = true
})
//当视频没有播放时展示图片
if (!this.isPlay) {
Image($r('sys.media.ohos_ic_public_play'))
.width('40%')
.fillColor('#deeeee')
//当点击图片时开始播放
.onClick(() => {
this.controller.start()
})
}
Text(this.item.title)
.fontSize(14)
.fontColor('#fff')
.padding(20)
}
}
}
忘了这个 @State currentIndex: number = 0 这个需要在声明一下,用来校验当前视频是否播放
完事,小demo结束~