HarmonyOS 5.0.0 或以上:实现一个长按按钮触发加速自增计数功能


📌 场景介绍

在一些场景(如加减数量、滑动选择值)中,长按加速操作可以提升体验,例如:

  • 长按“+”按钮:数字不断变大,越按越快

  • 松开立即停止

本篇实现一个带有长按加速效果的计数器按钮。


🧱 目录结构

/entry/src/main/ets
  ├── common/components/
  │   └── LongPressCounter.ets      // 长按加速计数按钮组件
  ├── pages/
  │   └── Index.ets                 // 使用示例

🧩 LongPressCounter.ets

@Component
export struct LongPressCounter {
  @State private count: number = 0
  private timer: number = -1
  private delay: number = 500 // 初始延迟
  private step: number = 1    // 每次加的值

  private startPress() {
    this.increment()
    this.timer = setInterval(() => {
      this.increment()
      // 越来越快
      if (this.delay > 50) {
        this.delay -= 50
        clearInterval(this.timer)
        this.startPress()
      }
    }, this.delay)
  }

  private stopPress() {
    if (this.timer !== -1) {
      clearInterval(this.timer)
      this.timer = -1
      this.delay = 500
    }
  }

  private increment() {
    this.count += this.step
  }

  build() {
    Column() {
      Text(`计数值: ${this.count}`).fontSize(24).margin(20)

      Button("+ 长按加速")
        .onTouch((event: TouchEvent) => {
          if (event.type === TouchType.Down) {
            this.startPress()
          } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
            this.stopPress()
          }
        })
        .margin(10)
        .width(200)
        .height(50)
    }
    .alignItems(HorizontalAlign.Center)
    .justifyContent(FlexAlign.Center)
    .height('100%')
  }
}

🧩 Index.ets 示例页面

@Entry
@Component
struct Index {
  build() {
    Column() {
      LongPressCounter()
    }
    .height('100%')
    .padding(20)
  }
}

✅ 效果说明

  • 点击按钮,计数 +1

  • 长按不放,数字加速上升

  • 松开立即停止


🔧 拓展建议

  • 实现“-”按钮支持递减

  • 增加最大值限制与回调

  • 用动画显示加速变化(如进度条)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值