实现效果
案例源码
@Component
export struct RefreshView{
@State marginTop:number = -80
touchDownY:number = 0
touchUpValue:number = -80
private intervalId: number = 0
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
private canRefresh:boolean = true
build() {
Column() {
Image($r("app.media.git_refresh"))
.width(80)
.height(80)
.margin({top:this.marginTop})
List({ space: 20, initialIndex: 0 }) {
ForEach(this.arr, (item) => {
ListItem() {
Text('' + item)
.width('100%').height(100).fontSize(16)
.textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF)
}.backgroundColor(Color.White).borderRadius(10)
}, item => item)
}
.listDirection(Axis.Vertical) // 排列方向
.edgeEffect(EdgeEffect.Spring) // 滑动到边缘无效果
.onScrollIndex((firstIndex: number, lastIndex: number) => {
this.canRefresh = firstIndex == 0
console.info('first' + firstIndex)
console.info('last' + lastIndex)
})
.width('90%')
.height('100%')
}
.backgroundColor($r("app.color.color_EEEEEE"))
.onTouch((event: TouchEvent) => {
if(this.canRefresh){
if (event.type === TouchType.Down) {
this.touchDownY = event.touches[0].y
}
if (event.type === TouchType.Up) {
this.touchUpValue = this.marginTop
if(this.marginTop < 0){
this.stopRefresh()
}else {
setTimeout(()=>{
this.stopRefresh()
},2000)
}
}
if (event.type === TouchType.Move) {
this.marginTop = this.touchUpValue + event.touches[0].y - this.touchDownY
if(this.marginTop >= 0){
this.marginTop = 0
}else if(this.marginTop <= -80){
this.marginTop = -80
}
}
}
})
.width('100%')
.height('100%')
}
updateAnim = ()=>{
this.marginTop = this.marginTop - 1
if(this.marginTop <= -80){
this.touchUpValue = -80
clearInterval(this.intervalId)
}
}
stopRefresh(){
this.intervalId = setInterval(this.updateAnim,3)
}
}