手势处理,在父布局移动 - HarmonyOS 鸿蒙Next

手势处理,在父布局移动 - HarmonyOS 鸿蒙Next

请对对子组件添加手势处理,达到四处移动的效果,但是我只希望它在父布局下移动,默认是可以全屏移动,可以解决吗

4 回复

可以参考以下demo,主要是搞清楚父组件的具体位置坐标,然后主动通过代码来限制,目前默认的手势是全屏的且无法通过api或者配置啥的限制在父组件内:

// xxx.ets
[@Entry](/user/Entry)
[@Component](/user/Component)
struct GestureGroupExample {
[@State](/user/State) count: number = 0
[@State](/user/State) offsetX: number = 0
[@State](/user/State) offsetY: number = 0
[@State](/user/State) positionX: number = 0
[@State](/user/State) positionY: number = 0
[@State](/user/State) borderStyles: BorderStyle = BorderStyle.Solid

build() {
Column() {
Text('sequence gesture\n' + 'LongPress onAction:' + this.count + '\nPanGesture offset:\nX: ' + this.offsetX +
'\n' + 'Y: ' + this.offsetY)
.fontSize(15)
}
.translate({ x: this.offsetX, y: this.offsetY, z: 0 })
.height(150)
.width(200)
.padding(20)
.margin(20)
.border({ width: 3, style: this.borderStyles })
.gesture(
// 以下组合手势为顺序识别,当长按手势事件未正常触发时则不会触发拖动手势事件
GestureGroup(GestureMode.Sequence,
LongPressGesture({ repeat: true })
.onAction((event?: GestureEvent) => {
if (event && event.repeat) {
this.count++
}
console.info('LongPress onAction')
}),
PanGesture()
.onActionStart(() => {
this.borderStyles = BorderStyle.Dashed
console.info('pan start')
})
.onActionUpdate((event?: GestureEvent) => {
if (event) {
if (this.positionX + event.offsetX <= 100 && this.positionX + event.offsetX >= 0) {
this.offsetX = this.positionX + event.offsetX
} else if (this.positionX + event.offsetX > 100) {
this.offsetX = 100
} else {
this.offsetX = 0
}
if (this.positionY + event.offsetY <= 200 && this.positionY + event.offsetY >= 0) {
this.offsetY = this.positionY + event.offsetY
} else if (this.positionY + event.offsetY > 200) {
this.offsetY = 200
} else {
this.offsetY = 0
}
}
console.info('pan update')
})
.onActionEnd(() => {
this.positionX = this.offsetX
this.positionY = this.offsetY
this.borderStyles = BorderStyle.Solid
console.info('pan end')
})
)
.onCancel(() => {
console.info('sequence gesture canceled')
})
)
}
}

更多关于手势处理,在父布局移动 - HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


是的,目前想到只能在代码中处理,想问一下移动用的是translate吗,使用position设置left和top进行定位可以吗

这里的x y 坐标是以左上角作为原点的,向右为x正,向下为y正,反方向为负,你说的position设置left和top进行定位也是可以的

在HarmonyOS鸿蒙Next系统中处理手势在父布局移动的问题,通常涉及到事件分发与拦截机制。以下是一些关键点,帮助你理解并可能解决这一问题:

  1. 事件分发机制:确保父布局正确实现onInterceptTouchEvent方法,以决定是否拦截手势事件。若希望手势在父布局中移动,父布局应拦截MotionEvent.ACTION_MOVE等事件。

  2. 子视图响应:若子视图也需要响应手势,可在子视图中处理事件,但需注意父布局是否已拦截。可通过requestDisallowInterceptTouchEvent(true)方法告知父布局不拦截特定事件。

  3. 手势识别器:使用GestureDetectorGestureDetectorCompat识别复杂手势,如滑动、缩放等,并在父布局中处理这些手势。

  4. 布局类型:检查父布局类型(如AbsoluteLayoutRelativeLayout等),某些布局可能对手势处理有特殊要求。

  5. 动画与滚动:若手势用于移动父布局内的内容,考虑使用ScrollerViewDragHelper辅助实现平滑滚动。

  6. 调试与日志:使用日志打印事件流向,确保事件按预期分发与拦截。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!