在HarmonyOS开发中,可通过状态管理结合定时器机制实现长按手势在60秒后主动终止。通过LongPressGesture的onAction回调启动定时器,结合状态变量控制手势终止逻辑:
@Component @Entry struct PressGestureDemo { @State isLongPressActive: boolean = true; // 控制手势激活状态 private timerId: number = 0; // 存储定时器ID build() { Row() { Column() { Button('长按60秒后自动终止') .gesture( LongPressGesture({ duration: 500 }) .onAction(() => { if (!this.isLongPressActive) { return; } // 状态终止时退出 // 启动60秒定时器 this.timerId = setTimeout(() => { this.isLongPressActive = false; // 此处可添加终止后的业务逻辑,即终止录音操作 }, 60000); }) .onActionEnd(() => { clearTimeout(this.timerId); // 清理定时器 this.isLongPressActive = true; // 重置状态 }) ); }.width('100%'); }.height('100%'); } }