📌 场景介绍
在一些场景(如加减数量、滑动选择值)中,长按加速操作可以提升体验,例如:
-
长按“+”按钮:数字不断变大,越按越快
-
松开立即停止
本篇实现一个带有长按加速效果的计数器按钮。
🧱 目录结构
/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
-
长按不放,数字加速上升
-
松开立即停止
🔧 拓展建议
-
实现“-”按钮支持递减
-
增加最大值限制与回调
-
用动画显示加速变化(如进度条)