一、功能简介

本篇将实现一个支持拖动滑块解锁的交互动画组件,结合拖拽动画、成功确认、归位弹性反馈,常用于安全验证、登录确认、界面切换等交互场景。


二、核心技术点

能力 实现方式
滑块拖动 PanGesture 监听水平滑动
成功判断 拖动距离超过阈值触发 unlock
弹性归位 未达标自动回弹,使用 .animate()
成功反馈 改变滑块颜色 + 状态提示

三、页面结构

entry/src/main/ets/pages/SliderUnlockDemo.ets

四、ArkTS 实战代码(SliderUnlockDemo.ets)

@Entry
@Component
struct SliderUnlockDemo {
  @State offsetX: number = 0
  @State unlocked: boolean = false
  private unlockThreshold: number = 220

  handleDrag(event: GestureEvent) {
    if (this.unlocked) return
    const nextX = this.offsetX + event.offsetX
    this.offsetX = Math.max(0, Math.min(nextX, this.unlockThreshold))
  }

  handleEnd() {
    if (this.offsetX >= this.unlockThreshold) {
      this.unlocked = true
    } else {
      this.offsetX = 0
    }
  }

  build() {
    Column() {
      Text('HarmonyOS 5.0.0 或以上')
        .fontSize(20)
        .margin({ bottom: 20 })

      Text(this.unlocked ? '✅ 解锁成功' : '请拖动滑块完成验证')
        .fontSize(16)
        .margin({ bottom: 20 })

      Stack() {
        // 背景条
        Box()
          .width(280).height(50)
          .borderRadius(25)
          .backgroundColor(this.unlocked ? '#4CAF50' : '#eeeeee')

        // 滑动轨迹进度
        Box()
          .width(this.offsetX + 50).height(50)
          .borderRadius(25)
          .backgroundColor(this.unlocked ? '#4CAF50' : '#a0c4ff')
          .animate({ duration: 200 })

        // 滑块按钮
        Box()
          .width(50).height(50)
          .borderRadius(25)
          .backgroundColor(this.unlocked ? '#388E3C' : '#007DFF')
          .translate({ x: this.offsetX })
          .animate({ duration: 200, curve: Curve.EaseOutBack })
          .gesture(
            PanGesture()
              .onActionUpdate(e => this.handleDrag(e))
              .onActionEnd(() => this.handleEnd())
          )
          .align(Alignment.Start)
      }
      .width(280).height(50)
    }
    .width('100%')
    .padding(20)
    .alignItems(HorizontalAlign.Center)
    .justifyContent(FlexAlign.Center)
    .backgroundColor('#f6f6f6')
  }
}

五、运行效果说明

  • 初始滑块停靠在左侧;
  • 用户拖动滑块,当拖动超过 220px 时判定为“解锁成功”;
  • 成功后滑块变色,背景显示绿色成功状态;
  • 未完成滑动松手则自动回弹,体现“弹性失败反馈”。

六、常见问题与优化建议

问题 原因 建议
滑块拖不动 未启用 PanGesture 或状态锁定 检查 unlocked 状态是否控制拖动逻辑
松手瞬间跳变 缺少动画修饰 .animate() 配合 EaseOutBack 增强弹性感
判定偏差 threshold 设置不合理 推荐为 轨道宽度 - 滑块宽度 的 80%~90%

七、拓展建议

  • 添加“重置滑动”按钮;
  • 拖动过程中加入文字进度提示;
  • 成功后联动跳转/表单提交;
  • 支持“向右滑动接听”等交互复用;
  • 封装为 <SlideToUnlock @success="onUnlock()" /> 通用组件。

下一篇为第22篇:

《HarmonyOS 5.0.0 或以上:实现背景模糊动画与弹窗蒙层融合动效》

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐