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

前言:

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
      })
   }
}
相关推荐
云和数据.ChenGuang14 分钟前
鸿蒙6的**星盾安全(StarShield)技术
安全·华为·harmonyos
2401_8396339116 分钟前
鸿蒙flutter第三方库适配 - 二维表格
flutter·华为·harmonyos
麒麟ZHAO17 分钟前
鸿蒙flutter第三方库适配 - Google登录演示
flutter·华为·harmonyos
SoraLuna18 分钟前
「鸿蒙智能体实战记录 12」快捷指令配置与真机逐条验证实现
华为·harmonyos
2401_8396339119 分钟前
鸿蒙flutter第三方库适配 - 日历网格
flutter·华为·harmonyos
2401_8396339119 分钟前
鸿蒙flutter第三方库适配 - 数据网格
flutter·华为·harmonyos
弓.长.26 分钟前
ReactNative for OpenHarmony项目鸿蒙化三方库:rn-placeholder — 骨架屏占位组件
react native·react.js·harmonyos
想你依然心痛29 分钟前
HarmonyOS 5.0医疗健康开发实战:构建分布式健康监测与AI预警系统
人工智能·分布式·harmonyos
见山是山-见水是水32 分钟前
鸿蒙flutter第三方库适配 - 汇率换算器
redis·flutter·华为·harmonyos
小菜刀_33 分钟前
OpenHarmony LiteOS-M Shell 命令开发指南
openharmony·loongarch·liteos-m