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

介绍

本示例实现了简单的滑动解锁按钮和倒计时结束按钮,能够实现滑动解锁,长按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
      })
  2. 按钮长按的加速结束时间的效果,也是依靠手势操作判断 - 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 声望0 粉丝