滑动解锁和倒计时按钮鸿蒙示例代码 原创

鸿蒙场景化示例代码技术工程师
发布于 2025-4-14 14:40
浏览
0收藏

本文原创发布在华为开发者社区

介绍

本示例实现了简单的滑动解锁按钮和倒计时结束按钮,能够实现滑动解锁,长按2秒结束或者按原设定时间结束。

滑动解锁和倒计时结束按钮源码链接

效果预览

滑动解锁和倒计时按钮鸿蒙示例代码-鸿蒙开发者社区

使用说明

运行项目前,请执行 ohpm install @ohos/hamock,下载hamock依赖

实现思路

  1. 滑动解锁依靠手势操作以及移动过程中的坐标计算更新来完成 - SlideButton
PanGesture(this.panOption)
  .onActionStart((event: GestureEvent) => {
  })
  .onActionUpdate((event: GestureEvent) => {
    if (this.disabled) {
      return;
    }
    if (this.sliderUnLockCompleted) {
      return;
    }
    // 计算当前水平方向上的偏移量
    this.offsetX = this.positionX + event.offsetX
    // 如果偏移量已经达到了最大长度即startMaxHeight,此时松开手,即可完成解锁
    if (this.offsetX < 0) {
      this.offsetX = 0
    } else if (this.offsetX > this.startMaxWeight) {
      this.offsetX = this.startMaxWeight
    } else {
      this.offsetX = this.positionX + event.offsetX
    }
  })
  .onActionEnd(() => {
    if (this.disabled) {
      return;
    }
    // 松手后判定当前偏移量是否已经达到最大值,若没有则回到原点,否则完成解锁
    if (this.offsetX < this.startMaxWeight) {
      // 回到原点
      this.offsetX = 0
    } else {
      this.offsetX = this.startMaxWeight;
      this.sliderUnLockCompleted = true;
      this.complete && this.complete(true);
    }
    this.positionX = this.offsetX
  })
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  1. 按钮长按的加速结束时间的效果,也是依靠手势操作判断 - LongPressButton
// 绑定可以重复触发的LongPressGesture
LongPressGesture({ repeat: true, duration: 200 })
  .onAction((event: GestureEvent | undefined) => {
    if (event) {
      this.pressStart = true;
      // 默认长按2s结束,可以改变increase来更改这个时间值
      if (event.repeat) {
        this.count += this.increase;
        hilog.info(0x0000, 'LongPressButton', 'pressStart', JSON.stringify(this.count))
      }
    }
  })
  .onActionEnd(() => {
    this.pressStart = false;
    hilog.info(0x0000, 'LongPressButton', 'onActionEnd', JSON.stringify(this.count), JSON.stringify(this.total))
    if (this.count < this.total) {
      this.pressEnd = false;
      this.count = this.tempCount;
    } else {
      clearInterval(this.timeout);
      this.pressEnd = true;
      this.complete && this.complete(true);
    }
})
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
分类
收藏
回复
举报


回复
    相关推荐