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

前言:

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
      })
   }
}
相关推荐
想你依然心痛5 分钟前
HarmonyOS 6(API 23)游戏开发实战:基于 Face AR & Body AR 的“律动星途“体感音游
华为·ar·harmonyos·body·face·悬浮导航·沉浸光感
liulian091621 分钟前
【Flutter for OpenHarmony 第三方库】Flutter for OpenHarmony 实时聊天功能适配与实现指南
flutter·华为·学习方法·harmonyos
Lanren的编程日记27 分钟前
Flutter 鸿蒙应用多设备同步功能实战:完整同步协议+冲突解决机制,打造跨设备一致体验
flutter·华为·harmonyos
想你依然心痛35 分钟前
HarmonyOS 6(API 23)实战:基于 Face AR 专注度检测与 Body AR 手势互动的“智能互动课堂“教师授课系统
华为·ar·harmonyos·悬浮导航·沉浸光感·face ar·body ar
小成Coder38 分钟前
【Jack实战】如何用 UserAuthenticationKit 给 HarmonyOS 应用加一道本地身份验证
华为·harmonyos
UnicornDev1 小时前
【HarmonyOS 6】设置页面 UI 设计
ui·华为·harmonyos·arkts·鸿蒙
Hello__777715 小时前
开源鸿蒙 Flutter 实战|消息通知功能完整实现
flutter·开源·harmonyos
敲代码的鱼哇17 小时前
发送短信/拨打电话/获取联系人能力 UTS 插件(cz-sms)
android·前端·ios·uni-app·安卓·harmonyos·鸿蒙
Hello__777717 小时前
开源鸿蒙 Flutter 实战|仓库评论与点赞功能完整实现
flutter·开源·harmonyos
代码飞天18 小时前
harmonyOS开发之页面跳转
华为·harmonyos