HarmonyOS 触控交互机制解析
触控交互机制涉及用户通过手指或手写笔在设备上进行的按下、滑动和释放操作,这些动作会触发相应的事件回调,包括单击、触摸和拖拽等类型。
1.1 单击操作
单击行为指用户完成按压与松开的完整动作,系统会通过特定回调函数传递坐标信息及事件源数据。
onTap(event: (event?: TapEvent) => void)
1.1.1 实现流程
实现触控响应需遵循以下步骤:
- 创建视图组件并设置唯一标识
- 绑定对应交互事件
- 实现事件处理接口
- 完成具体业务逻辑编写
1.1.2 事件绑定方式
(1)使用箭头函数直接绑定
Text('Tap Me')
.onTap(() => {
this.displayText = 'ArkUI';
})
(2)通过bind绑定上下文的匿名函数
Text('Add Value')
.onTap(function() {
this.counter += 2;
}.bind(this))
(3)引用类方法进行绑定
handleValueChange(): void {
this.counter += 2;
}
Text('Add Value')
.onTap(this.handleValueChange.bind(this))
(4)声明式函数绑定
updateCounter = () => {
console.info(`Current: ${this.counter}`);
this.counter++;
}
Text('Increment')
.onTap(this.updateCounter)
1.1.3 示例代码
import { promptAction, router } from '@kit.ArkUI'
import { RouterParams } from '@zzsKit/zzsLib'
import { TitleBar } from '../../../components/common/TitleBar'
@Extend(Text)
function itemStyle() {
.fontSize(17)
.backgroundColor($r('app.color.primary_green'))
.padding({ top: 8, bottom: 8, left: 70, right: 70 })
.margin({ top: 15, bottom: 15 })
}
@Entry
@Component
struct TouchPage {
@State title: string = "触控示例"
@State displayText: string = '等待操作'
aboutToAppear() {
try {
this.title = (router.getParams() as RouterParams).title
} catch (e) {}
}
handleTap() {
promptAction.showToast({ message: "触发操作" });
this.displayText = "已点击";
}
handleDetailedTap(event: TapEvent) {
promptAction.showToast({ message: "详细事件" });
this.displayText = `坐标:${JSON.stringify(event)}`;
}
build() {
Column() {
TitleBar({ pageTitle: $title })
Text('测试按钮')
.itemStyle()
.onTap((event: TapEvent) => {
this.displayText = "按钮1";
promptAction.showToast({ message: "按钮1" });
})
Text('按钮2')
.itemStyle()
.onTap(() => this.handleTap?.())
Text('按钮3')
.itemStyle()
.onTap(() => this.handleTap())
Text('按钮4')
.itemStyle()
.onTap((event: TapEvent) =>