HarmonyOS鸿蒙Next中在ArkUI如何使用GestureGroup实现手势的失败互斥识别
HarmonyOS鸿蒙Next中在ArkUI如何使用GestureGroup实现手势的失败互斥识别 实现一个条件手势:只有当轻击(TapGesture)识别失败时,另一个手势(例如拖拽 PanGesture)才能开始识别。如何通过 GestureGroup 的 GestureMode.Exclusive 模式实现这种依赖关系?
【解决方案】 开发者您好,请查看如下demo, 设置轻击允许的移动像素阈值distanceThreshold为15,避免轻微的颤抖而误触发:
// Index.ets
@Entry
@Component
struct Index {
@State message: string = '等待手势操作...';
@State offsetX: number = 0;
@State offsetY: number = 0;
build() {
Column() {
Text(this.message)
.fontSize(20)
.margin(20);
// 被操作的方块
Rect({ width: 150, height: 150 })
.fill(Color.Blue)
.translate({ x: this.offsetX, y: this.offsetY })
.gesture(
// 使用互斥模式管理手势组
GestureGroup(GestureMode.Exclusive,
// 1. 轻击手势
TapGesture({ count: 1, distanceThreshold: 15 }) // 设置轻击允许的移动像素阈值
.onAction(() => {
this.message = 'Tap手势识别成功(Pan未触发)';
}),
// 2. 拖拽手势
PanGesture({ fingers: 1 })
.onActionStart(() => {
this.message = 'Pan手势开始识别(Tap已宣告失败)';
})
.onActionUpdate((event: GestureEvent) => {
this.offsetX = event.offsetX;
this.offsetY = event.offsetY;
})
.onActionEnd(() => {
this.message = 'Pan手势结束';
})
)
);
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center);
}
}
如以上方案无法满足您的诉求,请及时反馈。
更多关于HarmonyOS鸿蒙Next中在ArkUI如何使用GestureGroup实现手势的失败互斥识别的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
没看懂
有点深奥
支持一下
在ArkUI中,使用GestureGroup的failureGesture属性实现失败互斥识别。定义多个手势并用failureGesture指定:若当前手势识别失败,则触发目标手势。示例:
GestureGroup({ failureGesture: gesture1 }) {
gesture1.onAction(() => ...)
gesture2.onAction(() => ...)
}
gesture1失败后尝试匹配gesture2。
使用 GestureGroup 的 GestureMode.Exclusive 模式,将 TapGesture 放在 PanGesture 之前,即可实现“轻击失败后才识别拖拽”。
GestureGroup(GestureMode.Exclusive,
TapGesture({ count: 1 })
.onAction((event: GestureEvent) => {
console.info('Tap success');
}),
PanGesture({ fingers: 1, distance: 5 })
.onActionUpdate((event: GestureEvent) => {
console.info('Dragging');
})
)
原理:
在 Exclusive 模式下,手势按添加顺序竞争。Tap 优先尝试识别,若手指按下后快速抬起,则 Tap 成功,Pan 被取消;若手指按下后未在超时内抬起(如开始拖拽),Tap 识别失败,Pan 接管并开始识别拖拽。这样便天然满足了“失败互斥”的条件。

