在HarmonyOS NEXT开发中把一个 Toggle 做成可拖动的,Toggle 类型是 Button,拖动时会触发 Toggle 的点击事件,有什么办法屏蔽吗?试了下只有类型是 Button 的时候有问题,Checkbox 和 Switch 正常
在HarmonyOS NEXT开发中把一个 Toggle 做成可拖动的,Toggle 类型是 Button,拖动时会触发 Toggle 的点击事件,有什么办法屏蔽吗?试了下只有类型是 Button 的时候有问题,Checkbox 和 Switch 正常
在 HarmonyOS NEXT 开发中,可以通过以下方案解决 Button 类型 Toggle 拖动触发点击事件的问题:
// 核心手势冲突处理逻辑
@State isDragging: boolean = false;
private startY: number = 0;
private dragThreshold: number = 5; // 拖动判定阈值
build() {
Toggle({ type: ToggleType.Button, isOn: false })
.onClick(() => {
if (!this.isDragging) {
// 正常点击逻辑
console.log('Toggle clicked');
}
})
.gesture(
PanGesture()
.onActionStart(() => {
this.startY = globalThis.pointerEvent?.y || 0;
this.isDragging = false;
})
.onActionUpdate((event: GestureEvent) => {
const dy = Math.abs(event.offsetY);
if (dy > this.dragThreshold) {
this.isDragging = true;
}
})
.onActionEnd(() => {
this.isDragging = false;
})
)
// 关键触摸事件拦截
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) {
// 接管触摸事件
}
})
}
实现原理:
PanGesture
手势识别拖动行为isDragging
标记当前是否处于拖动状态补充说明:
onClick
onTouch
事件可以更精确控制触摸事件传递扩展方案:
若需要更精确控制,可改用组合手势:
.gesture(
GestureGroup(
GesturePriority.Low,
PanGesture()
// ...同上手势逻辑
)
.onGestureJudge((gesture: GestureGroup, event: GestureEvent) => {
if (this.isDragging) {
gesture.setIntercept(true);
}
})
)
1 回答1.1k 阅读✓ 已解决
1 回答1.4k 阅读
1 回答1.2k 阅读
1 回答1.1k 阅读
1 回答1.1k 阅读
1 回答990 阅读
1 回答967 阅读
解决方案如下: