当前位置: 首页 > news >正文

【HarmonyOS开发】ArkUI实现下拉刷新/上拉加载

 列表下拉刷新、上拉加载更多,不管在web时代还是鸿蒙应用都是一个非常常用的功能,基于ArkUI中TS扩展的声明式开发范式实现一个下拉刷新,上拉加载。

上拉加载、下拉刷新

如果数据量过大,可以使用LazyForEach代替ForEach

高阶组件-上拉加载,下拉刷新icon-default.png?t=N7T8https://gitee.com/bingtengaoyu/harmonyos-advanced-componen/tree/master/UpDownRefresh 

1、涉及的知识点

  • 列表容器(List)
  • 触摸事件(onTouch)
  • 位置设置(offset)
  • 显示动画(animateTo)

2、效果图

3、实现思路

根据触摸事件onTouch()处理下拉和上拉,通过记录手指按下的y坐标和move移动的距离判断属于刷拉还是下滑,从而展示不同的内容。

4、关键代码

4.1 生成下拉刷新/上拉加载DOM

  @Builder UpDownRefreshBuilder(text: string, state: string) {Row() {Image($r('app.media.refreshing')).width(32).height(32)Text(text).fontSize(16)}.justifyContent(FlexAlign.Center).position({y: state === 'down' ? 20 : -20}).zIndex(999).width('94%').height('8%')}

4.2 onTouch处理事件

  private currentOffsetY: number = 0;private timer: number = 0;@State refreshStatus: boolean = false;@State upRefreshStatus: boolean = false;aboutToDisappear() {this.timer = null}putDownRefresh(event?: TouchEvent): void {if (event === undefined) {return;}switch (event.type) {case TouchType.Down:this.currentOffsetY = event.touches[0].y;break;case TouchType.Move:if(this.scroller.currentOffset().yOffset < 50) {this.refreshStatus = event.touches[0].y - this.currentOffsetY > 50;}this.upRefreshStatus = event.touches[0].y - this.currentOffsetY < -50;break;case TouchType.Cancel:break;case TouchType.Up:// Only simulation effect, no data requestthis.timer = setTimeout(() => {if (this.upRefreshStatus) {this.scroller.scrollTo({           // 调用scrollTo滚动到具体位置xOffset: 0,                    // 竖直方向滚动,该值不起作用yOffset: 680,    // 滚动到底部animation: {                     // 滚动动画duration: 1500,curve: Curve.EaseOut}})}this.refreshStatus = false;this.upRefreshStatus = false;}, 1500);break;}}

5、完整代码

兵腾傲宇/harmonyos-healthy-live - Gitee.com

import router from '@ohos.router'
import curves from '@ohos.curves'
import { BreakpointSystem, BreakPointType } from '../common/BreakpointSystem'
import { FoodInfo, Category } from '../model/DataModels'
import { getFoods, getFoodCategories, getSortedFoodData } from '../model/DataUtil'
import { Records } from './components/DietRecord'
import { PersonalCenter } from './PersonalCenter'interface FoodId {foodId: FoodInfo;
}@Component
struct FoodListItem {private foodItem?: FoodInfobuild() {Navigator({ target: 'pages/FoodDetail' }) {Row() {Image(this.foodItem!.image!).objectFit(ImageFit.Contain).autoResize(false).height(40).width(40).backgroundColor('#FFf1f3f5').margin({ right: 16 }).borderRadius(6).sharedTransition(this.foodItem!.letter, {duration: 400,curve: curves.cubicBezier(0.2, 0.2, 0.1, 1.0),delay: 100})Text(this.foodItem?.name).fontSize(14)Blank()Text($r('app.string.calorie_with_kcal_unit', this.foodItem?.calories.toString())).fontSize(14)}.height(64).width('100%')}.params({ foodId: this.foodItem } as FoodId).margin({ right: 24, left: 32 })}
}@Component
struct ListModeFoods {private foodItems: Array<FoodInfo | string> = getSortedFoodData()private currentOffsetY: number = 0;private timer: number = 0;@State refreshStatus: boolean = false;@State upRefreshStatus: boolean = false;aboutToDisappear() {this.timer = null}putDownRefresh(event?: TouchEvent): void {if (event === undefined) {return;}switch (event.type) {case TouchType.Down:this.currentOffsetY = event.touches[0].y;break;case TouchType.Move:if(this.scroller.currentOffset().yOffset < 50) {this.refreshStatus = event.touches[0].y - this.currentOffsetY > 50;}this.upRefreshStatus = event.touches[0].y - this.currentOffsetY < -50;break;case TouchType.Cancel:break;case TouchType.Up:// Only simulation effect, no data requestthis.timer = setTimeout(() => {if (this.upRefreshStatus) {this.scroller.scrollTo({           // 调用scrollTo滚动到具体位置xOffset: 0,                    // 竖直方向滚动,该值不起作用yOffset: 680,    // 滚动到底部animation: {                     // 滚动动画duration: 1500,curve: Curve.EaseOut}})}this.refreshStatus = false;this.upRefreshStatus = false;}, 1500);break;}}@Builder DownRefreshBuilder(text: string, state: string) {Row() {Image($r('app.media.refreshing')).width(32).height(32)Text(text).fontSize(16)}.justifyContent(FlexAlign.Center).position({y: state === 'down' ? 20 : -20}).zIndex(999).width('94%').height('8%')}private scroller: Scroller = new Scroller(); // 创建一个滚动控制器build() {Column() {Text($r("app.string.title_food_list")).width('100%').height(56).padding({ left: 20 }).backgroundColor('#FF1f3f5').fontSize(20)Scroll(this.scroller) {if(this.refreshStatus) {this.DownRefreshBuilder('正在刷新', 'down')}List() {ForEach(this.foodItems, (item: FoodInfo) => {ListItem() {if (item.letter !== undefined) {FoodListItem({ foodItem: item })} else {if (typeof (item) === 'string') {Text(item).fontSize(14).height(48).margin({ left: 24 }).width('100%')}}}})if(this.upRefreshStatus) {ListItem(){this.DownRefreshBuilder('正在加载', 'up')}}}.layoutWeight(1)}.scrollBar(BarState.Off).edgeEffect(EdgeEffect.Spring).width('100%').height('90%').onTouch((event?: TouchEvent) => {this.putDownRefresh(event);})}}
}@Component
struct FoodGridItem {private foodItem?: FoodInfobuild() {Column() {Image(this.foodItem!.image!).objectFit(ImageFit.Contain).backgroundColor('#f1f3f5').width('100%').height(152).sharedTransition(this.foodItem!.letter, {duration: 400,curve: curves.cubicBezier(0.2, 0.2, 0.1, 1.0),delay: 100})Row() {Text(this.foodItem?.name).fontSize(14)Blank()Text($r('app.string.calorie_with_kcal_unit', this.foodItem?.calories.toString())).fontSize(14).fontColor(0x99000000)}.padding({ left: 12, right: 12 }).width('100%').height(32).backgroundColor('#E5E5E5')}.height(184).clip(new Rect({ width: '100%', height: '100%', radius: 12 })).onClick(() => {router.pushUrl({ url: 'pages/FoodDetail', params: { foodId: this.foodItem } })})}
}@Component
struct FoodGrid {@StorageProp('currentBreakpoint') currentBreakpoint: string = 'sm'private foodItems?: FoodInfo[]build() {Grid() {ForEach(this.foodItems!, (item: FoodInfo) => {GridItem() {FoodGridItem({ foodItem: item })}})}.columnsTemplate(new BreakPointType({sm: '1fr 1fr',md: '1fr 1fr 1fr',lg: '1fr 1fr 1fr 1fr'}).getValue(this.currentBreakpoint) as string).columnsGap(8).rowsGap(8).padding({ left: 16, right: 16 })}
}@Component
struct CategoryModeFoods {@State currentTabIndex: number = 0private foodItems: FoodInfo[] = getFoods()private foodCategories: Category[] = getFoodCategories()/* ** 头部分类导航栏** */@BuildertabBarItemBuilder(value: Resource, index: number) {Text(value).fontColor(this.currentTabIndex === index ? Color.Blue : 'rgba(0,0,0,0.6)').fontSize(this.currentTabIndex === index ? 20 : 18).fontWeight(this.currentTabIndex === index ? FontWeight.Bold : FontWeight.Normal).margin({ top: 2 }).height(56)}build() {Tabs() {TabContent() {FoodGrid({ foodItems: this.foodItems })}.tabBar(this.tabBarItemBuilder($r('app.string.category_all'), 0))ForEach(this.foodCategories, (foodCategory: Category, index?: number) => {TabContent() {FoodGrid({ foodItems: this.foodItems.filter(item => (item.categoryId === foodCategory.id)) })}.tabBar(this.tabBarItemBuilder(foodCategory.name!,index! + 1))})}.animationDuration(0).barWidth('80%').onChange((index) => {this.currentTabIndex = index})}
}@Component
struct FoodsDisplay {@State isCategoryMode: boolean = true@State isMoreIconOnClick: boolean = false@State isMoreIconOnHover: boolean = false@State isMoreIconOnFocus: boolean = falsegetMoreIconBgColor() {if (this.isMoreIconOnClick) {return $r('sys.color.ohos_id_color_click_effect')} else if (this.isMoreIconOnHover) {return $r('sys.color.ohos_id_color_hover')} else {return this.isCategoryMode ? Color.White : '#F1F3F5' || Color.Transparent}}build() {Stack({ alignContent: Alignment.TopEnd }) {if (this.isCategoryMode) {CategoryModeFoods()} else {ListModeFoods()}Row() {Image($r("app.media.ic_switch")).height(24).width(24).margin({ left: 24, right: 24 }).focusable(true)}.height(56).backgroundColor(this.getMoreIconBgColor()).stateStyles({focused: {.border({radius: $r('sys.float.ohos_id_corner_radius_clicked'),color: $r('sys.color.ohos_id_color_focused_outline'),style: BorderStyle.Solid})},normal: {.border({radius: $r('sys.float.ohos_id_corner_radius_clicked'),width: 0})}}).onFocus(() => this.isMoreIconOnFocus = true).onBlur(() => this.isMoreIconOnFocus = false).onHover((isOn) => this.isMoreIconOnHover = isOn).onClick(() => {this.isCategoryMode = !this.isCategoryMode})}}
}@Entry
@Component
struct Home {@State currentTabIndex: number = 0@StorageProp('currentBreakpoint') currentBreakpoint: string = 'sm'private breakpointSystem: BreakpointSystem = new BreakpointSystem()/* ** 主页和记录的tabs* */@BuilderbottomBarItemBuilder(name: Resource, icon: Resource, index: number) {Flex({direction: new BreakPointType({sm: FlexDirection.Column,md: FlexDirection.Row,lg: FlexDirection.Column}).getValue(this.currentBreakpoint),justifyContent: FlexAlign.Center,alignItems: ItemAlign.Center}) {Image(icon).height(24).width(24).fillColor(this.getTabBarColor(index))Text(name).margin(new BreakPointType<Padding>({sm: { top: 4 },md: { left: 8 },lg: { top: 4 }}).getValue(this.currentBreakpoint) as Padding).fontSize(11).fontColor(this.getTabBarColor(index))}}aboutToAppear() {this.breakpointSystem.register()}aboutToDisappear() {this.breakpointSystem.unregister()}build() {Tabs({barPosition: new BreakPointType({sm: BarPosition.End,md: BarPosition.End,lg: BarPosition.Start}).getValue(this.currentBreakpoint)}) {TabContent() {FoodsDisplay()}.tabBar(this.bottomBarItemBuilder($r("app.string.tab_bar_home"), $r("app.media.ic_bottom_home"), 0))TabContent() {Records()}.tabBar(this.bottomBarItemBuilder($r("app.string.tab_bar_record"), $r("app.media.ic_bottom_record"), 1))TabContent() {PersonalCenter()}.tabBar(this.bottomBarItemBuilder($r("app.string.tab_bar_me"), $r("app.media.ic_public_me"), 2))}.vertical(new BreakPointType({ sm: false, md: false, lg: true }).getValue(this.currentBreakpoint) as boolean).barWidth(new BreakPointType({ sm: '100%', md: '100%', lg: '56vp' }).getValue(this.currentBreakpoint) as string).barHeight(new BreakPointType({ sm: '56vp', md: '56vp', lg: '60%' }).getValue(this.currentBreakpoint) as string).animationDuration(300).onChange((index) => {this.currentTabIndex = index})}private getTabBarColor(index: number) {return this.currentTabIndex == index ? $r('app.color.tab_bar_select_color') : $r('app.color.tab_bar_normal_color')}
}

6、另外一个思路实现上拉加载,下拉刷新

根据List中的回调方法onScrollIndex()监听当前列表首尾索引,根据触摸事件onTouch()处理下拉和上拉。

const TopHeight = 200;@Entry
@Component
struct Index {@State list: Array<number> = []// 列表y坐标偏移量@State offsetY: number = 0// 按下的y坐标private downY = 0// 上一次移动的y坐标private lastMoveY = 0// 当前列表首部的索引private startIndex = 0// 当前列表尾部的索引private endIndex = 0// 下拉刷新的布局高度private pullRefreshHeight = 70// 下拉刷新文字:下拉刷新、松开刷新、正在刷新、刷新成功@State pullRefreshText: string= '下拉刷新'// 下拉刷新图标:与文字对应@State pullRefreshImage: Resource = $r("app.media.ic_pull_refresh_down")// 是否可以刷新:未达到刷新条件,收缩回去private isCanRefresh = false// 是否正在刷新:刷新中不进入触摸逻辑private isRefreshing: boolean = false// 是否已经进入了下拉刷新操作private isPullRefreshOperation = false// 上拉加载的布局默认高度private loadMoreHeight = 70// 上拉加载的布局是否显示@State isVisibleLoadMore: boolean = false// 是否可以加载更多private isCanLoadMore = false// 是否加载中:加载中不进入触摸逻辑private isLoading: boolean = false// 自定义下拉刷新布局@Builder CustomPullRefreshLayout(){Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {Image(this.pullRefreshImage).width(18).height(18)Text(this.pullRefreshText).margin({ left: 7, bottom: 1 }).fontSize(17)}.width('100%').height(this.pullRefreshHeight)// 布局跟着列表偏移量移动.offset({ x: 0, y: `${vp2px(-this.pullRefreshHeight) + this.offsetY}px` })}// 自定义加载更多布局@Builder CustomLoadMoreLayout(){Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {Image($r("app.media.ic_loading")).width(18).height(18)Text('加载更多中...').margin({ left: 7, bottom: 1 }).fontSize(17)}.width('100%').height(this.loadMoreHeight).backgroundColor('#f4f4f4').visibility(this.isVisibleLoadMore ? Visibility.Visible : Visibility.None)}// 刷新测试数据private refreshData(){this.list = []for (var i = 0; i < 15; i++) {this.list.push(i)}}// 加载更多测试数据private loadMoreData(){let initValue = this.list[this.list.length-1] + 1for (var i = initValue; i < initValue + 10; i++) {this.list.push(i)}}build() {Column() {// 下拉刷新布局this.CustomPullRefreshLayout()// 列表布局List() {ForEach(this.list, item => {ListItem() {Column() {Text(`Item ${item}`).padding(15).fontSize(18)}}}, item => item.toString())// 加载更多布局ListItem(){this.CustomLoadMoreLayout()}}.backgroundColor(Color.White) // 背景.divider({ color: '#e2e2e2', strokeWidth: 1 }) // 分割线.edgeEffect(EdgeEffect.None) // 去掉回弹效果.offset({ x: 0, y: `${this.offsetY - TopHeight}px` }) // touch事件计算的偏移量单位是px,记得加上单位.onScrollIndex((start, end) => { // 监听当前列表首位索引console.info(`${start}=start============end=${end}`)this.startIndex = startthis.endIndex = end})}.width('100%').height('100%').backgroundColor('#f4f4f4').onTouch((event) => this.listTouchEvent(event))// 父容器设置touch事件,当列表无数据也可以下拉刷新.onAppear(() => {this.refreshData()})}// 触摸事件listTouchEvent(event: TouchEvent){switch (event.type) {case TouchType.Down: // 手指按下// 记录按下的y坐标this.downY = event.touches[0].ythis.lastMoveY = event.touches[0].ybreakcase TouchType.Move: // 手指移动// 下拉刷新中 或 加载更多中,不进入处理逻辑if(this.isRefreshing || this.isLoading){console.info('========Move刷新中,返回=========')return}// 判断手势let isDownPull = event.touches[0].y - this.lastMoveY > 0// 下拉手势 或 已经进入了下拉刷新操作if ((isDownPull || this.isPullRefreshOperation) && !this.isCanLoadMore) {this.touchMovePullRefresh(event)} else {this.touchMoveLoadMore(event)}this.lastMoveY = event.touches[0].ybreakcase TouchType.Up: // 手指抬起case TouchType.Cancel: // 触摸意外中断:来电界面// 刷新中 或 加载更多中,不进入处理逻辑if(this.isRefreshing || this.isLoading){console.info('========Up刷新中,返回=========')return}if (this.isPullRefreshOperation) {this.touchUpPullRefresh()} else {this.touchUpLoadMore()}break}}//============================================下拉刷新==================================================// 手指移动,处理下拉刷新touchMovePullRefresh(event:TouchEvent){// 当首部索引位于0if (this.startIndex == 0) {this.isPullRefreshOperation = true// 下拉刷新布局高度var height = vp2px(this.pullRefreshHeight)// 滑动的偏移量this.offsetY = event.touches[0].y - this.downY// 偏移量大于下拉刷新布局高度,达到刷新条件if (this.offsetY >= height) {// 状态1:松开刷新this.pullRefreshState(1)// 偏移量的值缓慢增加this.offsetY = height + this.offsetY * 0.15} else {// 状态0:下拉刷新this.pullRefreshState(0)}if (this.offsetY < 0) {this.offsetY = 0this.isPullRefreshOperation = false}}}// 手指抬起,处理下拉刷新touchUpPullRefresh(){// 是否可以刷新if (this.isCanRefresh) {console.info('======执行下拉刷新========')// 偏移量为下拉刷新布局高度this.offsetY = vp2px(this.pullRefreshHeight)// 状态2:正在刷新this.pullRefreshState(2)// 模拟耗时操作setTimeout(() => {this.refreshData()this.closeRefresh()}, 2000)} else {console.info('======关闭下拉刷新!未达到条件========')// 关闭刷新this.closeRefresh()}}// 下拉刷新状态// 0下拉刷新、1松开刷新、2正在刷新、3刷新成功pullRefreshState(state:number){switch (state) {case 0:// 初始状态this.pullRefreshText = '下拉刷新'this.pullRefreshImage = $r("app.media.ic_pull_refresh_down")this.isCanRefresh = falsethis.isRefreshing = falsebreak;case 1:this.pullRefreshText = '松开刷新'this.pullRefreshImage = $r("app.media.ic_pull_refresh_up")this.isCanRefresh = truethis.isRefreshing = falsebreak;case 2:this.offsetY = vp2px(this.pullRefreshHeight)this.pullRefreshText = '正在刷新'this.pullRefreshImage = $r("app.media.ic_loading")this.isCanRefresh = truethis.isRefreshing = truebreak;case 3:this.pullRefreshText = '刷新成功'this.pullRefreshImage = $r("app.media.ic_refresh_succeed")this.isCanRefresh = truethis.isRefreshing = truebreak;}}// 关闭刷新closeRefresh() {// 如果允许刷新,延迟进入,为了显示刷新中setTimeout(() => {var delay = 50if (this.isCanRefresh) {// 状态3:刷新成功this.pullRefreshState(3)// 为了显示刷新成功,延迟执行收缩动画delay = 500}animateTo({duration: 150, // 动画时长delay: delay, // 延迟时长onFinish: () => {// 状态0:下拉刷新this.pullRefreshState(0)this.isPullRefreshOperation = false}}, () => {this.offsetY = 0})}, this.isCanRefresh ? 500 : 0)}//============================================加载更多==================================================// 手指移动,处理加载更多touchMoveLoadMore(event:TouchEvent) {// 因为加载更多是在列表后面新增一个item,当一屏能够展示全部列表,endIndex 为 length+1if (this.endIndex == this.list.length - 1 || this.endIndex == this.list.length) {// 滑动的偏移量this.offsetY = event.touches[0].y - this.downYif (Math.abs(this.offsetY) > vp2px(this.loadMoreHeight)/2) {// 可以刷新了this.isCanLoadMore = true// 显示加载更多布局this.isVisibleLoadMore = true// 偏移量缓慢增加this.offsetY = - vp2px(this.loadMoreHeight) + this.offsetY * 0.1}}}// 手指抬起,处理加载更多touchUpLoadMore() {animateTo({duration: 200, // 动画时长}, () => {// 偏移量设置为0this.offsetY = 0})if (this.isCanLoadMore) {console.info('======执行加载更多========')// 加载中...this.isLoading = true// 模拟耗时操作setTimeout(() => {this.closeLoadMore()this.loadMoreData()}, 2000)} else {console.info('======关闭加载更多!未达到条件========')this.closeLoadMore()}}// 关闭加载更多closeLoadMore() {this.isCanLoadMore = falsethis.isLoading = falsethis.isVisibleLoadMore = false}}

相关文章:

  • drf知识--01
  • 隐藏通信隧道技术——防御SSH隧道攻击的思路
  • QT GUI代码大全(MainWindow, QFile, QPainter, QGraphicsItem/Scene/View)
  • SSH免密登录
  • leetcode 525. 连续数组(优质解法)
  • 使用包、Crate 和模块管理项目(下)
  • 性能压力测试--确保企业数字化业务稳健运行
  • 前端:NPM的介绍和使用
  • 杰发科技AC7840——在Eclipse环境下使用Jlink调试
  • SSM整合实战(Spring、SpringMVC、MyBatis)
  • 大模型赋能“AI+电商”,景联文科技提供高质量电商场景数据
  • flowable工作流学习笔记
  • 针对这两个趋势,3.0全新新零售商业模式可以采取以下策略:
  • 【WeLink群消息机器人webhook介绍】
  • 将Abp默认事件总线改造为分布式事件总线
  • ----------
  • [原]深入对比数据科学工具箱:Python和R 非结构化数据的结构化
  • classpath对获取配置文件的影响
  • Docker入门(二) - Dockerfile
  • ES10 特性的完整指南
  • HTTP请求重发
  • MQ框架的比较
  • ng6--错误信息小结(持续更新)
  • PHP 程序员也能做的 Java 开发 30分钟使用 netty 轻松打造一个高性能 websocket 服务...
  • SSH 免密登录
  • UMLCHINA 首席专家潘加宇鼎力推荐
  • Vue学习第二天
  • 从零开始在ubuntu上搭建node开发环境
  • 大快搜索数据爬虫技术实例安装教学篇
  • 服务器之间,相同帐号,实现免密钥登录
  • 深入体验bash on windows,在windows上搭建原生的linux开发环境,酷!
  • 阿里云API、SDK和CLI应用实践方案
  • 基于django的视频点播网站开发-step3-注册登录功能 ...
  • ​第20课 在Android Native开发中加入新的C++类
  • #if #elif #endif
  • #中国IT界的第一本漂流日记 传递IT正能量# 【分享得“IT漂友”勋章】
  • $分析了六十多年间100万字的政府工作报告,我看到了这样的变迁
  • (2021|NIPS,扩散,无条件分数估计,条件分数估计)无分类器引导扩散
  • (cos^2 X)的定积分,求积分 ∫sin^2(x) dx
  • (echarts)echarts使用时重新加载数据之前的数据存留在图上的问题
  • (LeetCode C++)盛最多水的容器
  • (Redis使用系列) SpirngBoot中关于Redis的值的各种方式的存储与取出 三
  • (免费领源码)python#django#mysql校园校园宿舍管理系统84831-计算机毕业设计项目选题推荐
  • (十六)Flask之蓝图
  • (转载)PyTorch代码规范最佳实践和样式指南
  • .【机器学习】隐马尔可夫模型(Hidden Markov Model,HMM)
  • .net core 6 使用注解自动注入实例,无需构造注入 autowrite4net
  • .NET Core WebAPI中封装Swagger配置
  • .NET Core工程编译事件$(TargetDir)变量为空引发的思考
  • .NET Micro Framework初体验
  • .NET 应用架构指导 V2 学习笔记(一) 软件架构的关键原则
  • .NETCORE 开发登录接口MFA谷歌多因子身份验证
  • .net程序集学习心得
  • .Net程序猿乐Android发展---(10)框架布局FrameLayout
  • ::什么意思