在移动应用中,各种列表页面离不开下拉刷新和上拉加载更多,我们的商城应用也是如此。今天介绍一下在仓颉开发语言中如何实现这一功能。
下拉刷新

仓颉开发语言直接提供了下拉刷新的组件,叫做Refresh,使用起来也非常方便:
less
@State var headerLoading : Bool = false;
Refresh(RefreshParams(refreshing: @Binder(this.headerLoading))) {
List{
ForEach(this.carList,
itemGeneratorFunc:{
item:CarItem, index: Int64 => ListItem {
}
})
}
}
.onRefreshing({ =>
Timer.once(Duration.second*2,{=>
this.headerLoading = false
})
AppLog.info('onRefreshing')
})
.onStateChange({state =>
AppLog.info('onStateChange')
})
上述代码演示了Refresh的基本使用,并且使用计时器模拟网络加载效果,两秒后自动加载完成,其中onRefreshing是进入刷新状态的回调,onStateChange为刷新状态改变的回调。
计时器的用法也还需要大家再次熟悉一下,Timer.once表示一次性的计时器,Duration.second*2表示执行间隔是2秒,这种写法还是比较独特的。
上拉加载更多
关于上拉加载更多,仓颉的文档中并没有这部分的内容,幽蓝君参考ArkTs写了一个解决方案,仅供大家参考。

实现思路是在List最后一行添加加载动画组件,默认隐藏,当List滑动到最后一行则显示加载动画并开始请求数据,具体代码如下:
scss
@State var footerLoading:Bool = false
List{
ForEach(this.carList,
itemGeneratorFunc:{
item:CarItem, index: Int64 => ListItem {
}
})
ListItem {
if(this.footerLoading){
Row(12){
LoadingProgress()
.height(40)
.width(40)
Text('加载中...')
.fontSize(14)
.fontColor(Color.GRAY)
}
.width(100.percent)
.height(50)
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.Center)
}
}
}
.onScrollIndex({startNum,endNum =>
if(Int64(endNum) >= this.carList.size - 1){
this.footerLoading = true
Timer.once(Duration.second*3,{=>
this.footerLoading = false
})
}
CJTools.log('endNum-list:' + this.carList.size.toString())
})
上面代码需要注意的是如何判断列表滑动到了底部,主要是判断数组的长度,在仓颉中数组的长度属性是size,类型是Int64。
以上就是今天的内容分享,感谢阅读。##HarmonyOS语言##仓颉##购物#