滑动解锁和倒计时结束按钮示例

77 阅读1分钟

介绍

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

效果预览

image

使用说明

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

权限说明

暂无

约束与限制

1.本示例仅支持标准系统上运行,支持设备:华为手机。

2.HarmonyOS系统:HarmonyOS NEXT Release及以上。

3.DevEco Studio版本:DevEco Studio 5.0.1 Release及以上。

4.HarmonyOS SDK版本:HarmonyOS 5.0.1 Release SDK及以上。

实现思路

  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. 按钮长按的加速结束时间的效果,也是依靠手势操作判断 - 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);
    }
})

工程目录

entry/src/main/
|---ets
|   |---entryability
|   |---entrybackupability
|   |---components
|   |   |---LongPressButton.ets                // 倒计时结束按钮
|   |   |---SlideButton.ets                    // 滑动解锁
|   |---MainAbility
|   |---pages
|   |   |---index.ets                          // 首页
|---resources
|   |---base
|   |---en_US
|   |---rawfile
|   |---zn_CN
|---module.json5

模块依赖

暂无

参考文档

ChangeLog

2024/11/19 1.滑动解锁和倒计时结束按钮demo

本文由博客一文多发平台 OpenWrite 发布!