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

前言:

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
      })
   }
}
相关推荐
用户593096009783 小时前
Flutter 鸿蒙化实战:r_upgrade 适配 OpenHarmony,应用升级检查与弹窗
harmonyos
youyin3 小时前
HarmonyOS 鸿蒙 ArkTS/ArkUI 装饰器大全
华为·harmonyos
轻口味4 小时前
HarmonyOS 7 新特性1:闪控窗——轻规划里的专注倒计时,跟着你走出应用
harmonyos·鸿蒙·移动端·闪控窗
用户593096009784 小时前
Flutter 鸿蒙化实战:record_mp3 适配 OpenHarmony,边录音边出 MP3
harmonyos
youyin5 小时前
HarmonyOS ArkTS 与智能融合案例之实时语音翻译应用 实验指导书和代码
华为·harmonyos
木子雨廷5 小时前
第 16 天|网络四态:loading、error、empty、content
harmonyos
用户593096009785 小时前
Flutter 鸿蒙化实战:open_app_settings 适配 OpenHarmony,一键跳转系统设置
harmonyos
贾伟康5 小时前
【HarmonyOS 7新能力|047】ModularObjectExtensionAbility工程封装:把接入逻辑放进可维护的分层结构
harmonyos·arkts·模块化架构·跨应用调用·abilitykit
李游Leo5 小时前
HarmonyOS 7 ArkTS 并发实战:Sendable、共享模块与跨线程对象传递机制
harmonyos
骑着蜗牛撵大象3277 小时前
从跨平台Linux到鸿蒙PC:基于Qt C++的Flameshot截图工具源码级适配
harmonyos·鸿蒙·es