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

前言:

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
      })
   }
}
相关推荐
奶糖不太甜33 分钟前
鸿蒙图片资源加载全攻略:从基础到性能优化
harmonyos·图片资源
小小小小小星38 分钟前
鸿蒙多端适配开发指南:从入门到实战
harmonyos
鸿蒙小灰1 小时前
鸿蒙开发之仿抖音APP教程:方法论与技术探索
harmonyos
CC__xy1 小时前
04 类型别名type + 检测数据类型(typeof+instanceof) + 空安全+剩余和展开(运算符 ...)简单类型和复杂类型 + 模块化
开发语言·javascript·harmonyos·鸿蒙
鸿蒙先行者1 小时前
鸿蒙开发ArkUI框架布局与适配难题丛生之响应式布局实现艰难
harmonyos·arkui
ajassi20002 小时前
开源 Arkts 鸿蒙应用 开发(十七)通讯--http多文件下载
华为·开源·harmonyos
前端世界2 小时前
在鸿蒙里优雅地处理网络错误:从 Demo 到实战案例
网络·华为·harmonyos
changsanjiang2 小时前
鸿蒙 音视频边播放边缓存
harmonyos
Georgewu6 小时前
【HarmonyOS】应用调用相机功能(扫码,自定义相机,人脸活体检测等)显示黑屏
harmonyos
文博知浅7 小时前
时隔4个月,500+star,鸿蒙ArkTS vscode插件1.x已发布🎉完全重构,补全、类型提示、SDK下载管理切换一应俱全,更多新功能正在规划中...
前端·javascript·harmonyos