鸿蒙实现一种仿小红书首页滑动联动效果

前言:

DevEco Studio版本:4.0.0.600

效果描述:通过手指滑动列表,控制位置显示效果为:不论列表在什么位置下滑时下图粉色位置布局显示,手指上滑时下图粉色位置布局隐藏。

效果:

原理分析:

通过给List列表设置触摸监听(onTouch ),然后监听手指滑动的按下位置,和滑动时的位置,依据这两个数据的差值来判断,列表是上滑动还是下滑。然后通过animateTo动画动态来控制操作布局的高度,来达到显示和隐藏的效果。

代码实现:

复制代码
@Entry
@Component
struct Index12 {
   @State newsList: string[] = []

   aboutToAppear() {
      //假数据
      for (let index = 0; index < 30; index++) {
         this.newsList[index] = '测试数据: ' + index
      }
   }

   build() {
      Flex({ direction: FlexDirection.Column }) {

         Text('头部固定位置布局')
            .fontColor(Color.White)
            .width('100%')
            .height(30)
            .backgroundColor(Color.Blue)

         Text('手指下滑时显示,手指上滑时隐藏布局')
            .width('100%')
            .height(this.textHeight)
            .backgroundColor(Color.Pink)

         List() {
            ForEach(this.newsList, (item: string) => {
               ListItem() {
                  Column() {
                     Text(item).width('100%').height(100).textAlign(TextAlign.Center).backgroundColor(Color.White)
                     Divider().strokeWidth(1).color('#000000')
                  }
               }
            }, (item: string) => item)
         }
         .width('100%')
         .height('100%')
         .sticky(StickyStyle.Header)
         .edgeEffect(EdgeEffect.None)
         .onTouch((event) => this.touchEvent(event))
      }
   }

   private downY: number = 0 // 记录按下的y坐标
   @State textHeight: number = 50

   touchEvent(event: TouchEvent) {
      switch (event.type) {
         case TouchType.Down: // 手指按下
            this.downY = event.touches[0].y
            break
         case TouchType.Move: // 手指移动
            let difY = event.touches[0].y - this.downY
            if (difY > 0) { //手指向下滑动
               this.showTitle()
            } else { //手指向上滑动
               this.hideTitle()
            }
            break
      }
   }

   private showTitle() {
      animateTo({ duration: 300 }, () => {
         this.textHeight = 50
      })
   }

   private hideTitle() {
      animateTo({ duration: 300 }, () => {
         this.textHeight = 0
      })
   }
}
相关推荐
大雷神26 分钟前
HarmonyOS APP<玩转React>开源教程四:状态管理基础
react.js·开源·harmonyos
前端不太难1 小时前
90% 的鸿蒙 App,没有真正的依赖管理
华为·状态模式·harmonyos
小白学鸿蒙3 小时前
openharmony老项目迁移新项目结构踩坑记录
鸿蒙·openharmony
左手厨刀右手茼蒿4 小时前
Flutter 三方库 build_modules 的鸿蒙化适配指南 - 在鸿蒙系统上构建极致、模块化的 Dart 代码编译策略与构建流水线系统
flutter·harmonyos·鸿蒙·openharmony·build_modules
MardaWang5 小时前
鸿蒙App内存排查与监控全链路实战(工具+方案)
华为·面试·harmonyos·鸿蒙
是稻香啊19 小时前
HarmonyOS6 ArkUI 触摸拦截(onTouchIntercept)全面解析与实战演示
ubuntu·华为·harmonyos·harmonyos6
是稻香啊20 小时前
HarmonyOS6 ArkUI 子组件触摸测试控制(onChildTouchTest)全面解析与实战演示
华为·harmonyos·harmonyos6
fei_sun1 天前
【鸿蒙智能硬件】(一)环境配置
华为·harmonyos
大雷神1 天前
HarmonyOS APP<玩转React>开源教程一:开发环境搭建与项目创建
harmonyos
HarmonyOS_SDK1 天前
高德地图携手HamonyOS SDK,首发鸿蒙AR实景步导
harmonyos