当前位置:   article > 正文

HarmonyOS开发(十二):ArkTS组件通用事件_鸿蒙arkts开发 监听返回

鸿蒙arkts开发 监听返回

1、ArkTS组件通用事件

1.1、点击事件

onClick(event:(event?:ClickEvent) => void)

不支持冒泡

点击动作触发该回调,支持在卡片中使用

ClickEvent对象说明

名称类型描述
screenXnumber点击位置相对于应用窗口左上角的X坐标
screenYnumber点击位置相对于应用窗口左上解的Y坐标
xnumber点击位置相对于被点击元素左上角的X坐标
ynuumber点击位置相对于被点击元素左上角的y坐标
timestampnumber事件的时间戳,单位纳秒
targetEventTarget

触发事件的元素对象显示区域

区域是一个Area类型数据

sourceSourceType事件输入设备

  1. @Entry
  2. @Component
  3. struct ClickTest {
  4. @State text: string = ''
  5. build() {
  6. Column() {
  7. Row({space:20}) {
  8. Button('Click').width(100).height(40)
  9. .onClick((event:ClickEvent) => {
  10. this.text = 'Click Point:' + '\n screenX:' + event.screenX + '\n screenY:' + event.screenY
  11. + '\n x:' + event.x + '\n y:' + event.y + '\ntarget:' + '\n component globalPos:('
  12. + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\n width:'
  13. + event.target.area.width + '\n height:' + event.target.area.height + '\ntimestamp:' + event.timestamp;
  14. })
  15. Button('Click').width(200).height(50)
  16. .onClick((event:ClickEvent) => {
  17. this.text = 'Click Point:' + '\n screenX:' + event.screenX + '\n screenY:' + event.screenY
  18. + '\n x:' + event.x + '\n y:' + event.y + '\ntarget:' + '\n component globalPos:('
  19. + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\n width:'
  20. + event.target.area.width + '\n height:' + event.target.area.height + '\ntimestamp:' + event.timestamp;
  21. })
  22. }.margin(20)
  23. Text(this.text).margin(15)
  24. }.width('100%')
  25. }
  26. }

1.2、触摸事件

当手指在组件上按下、滑动、抬起时触发

onTouch(event:(event?:TouchEvent)=>void)

支持冒泡

手指触摸动作触发这个回调

TouchEvent对象说明

名称类型描述
typeTouchType触摸事件的类型
touchesArray<TouchObject>全部手指信息
changedTouchesArray<TouchObject>当前发生变化的和指信息
stopPropagation() => void阻塞事件冒泡
timestampnumber

事件的时间戳,单位纳秒

距离系统启动的时间间隔

targetEventTarget触发事件的元素对象显示区域
sourceSourceType事件输入设备

TouchObject对象说明

名称类型描述
typeTouchType触摸事件的类型
idnumber手指唯一标识符
screenXnumber触摸点相对于应用窗口左上角的X坐标
screenYnumber触摸点相对于应用窗口左上角的Y坐标
xnumber触摸点相对于被触摸元素左上角的X坐标
ynumber触摸点相对于被触摸元素左上解的Y坐标

  1. @Entry
  2. @Component
  3. struct TouchTest {
  4. @State text: string = ''
  5. @State eventType: string = ''
  6. build() {
  7. Column(){
  8. Button('Touch').height(40).width(100)
  9. .onTouch((event:TouchEvent) => {
  10. if(event.type === TouchType.Down) {
  11. this.eventType = 'Down'
  12. }
  13. if(event.type === TouchType.Up) {
  14. this.eventType = 'Up'
  15. }
  16. if(event.type === TouchType.Move) {
  17. this.eventType = 'Move'
  18. }
  19. this.text = 'TouchType:\t' + this.eventType + '\nDistance between touch point and touch element:\nx:\t'
  20. + event.touches[0].x + '\n' + 'y:\t' + event.touches[0].y + '\nComponent globalPos: ('
  21. + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:\t'
  22. + event.target.area.width + '\nheight:\t' + event.target.area.height
  23. })
  24. Text(this.text)
  25. }
  26. .width('100%').padding(30)
  27. }
  28. }

1.3、挂载卸载事件

挂载卸载事件指组件从组件树上挂载、卸载时触发的事件

onAppear(event:()=>void)

组件挂载显示时触发此回调

不支持冒泡

onDisAppear(event:()=>void)

组件卸载消失时触发此回调

不支持冒泡

  1. import promptAction from '@ohos.promptAction'
  2. @Entry
  3. @Component
  4. struct AppearTest {
  5. @State isShow: boolean = true
  6. @State changeAppear: string = '点我卸载挂载组件'
  7. private myText: string = 'Text for onAppear'
  8. build() {
  9. Column(){
  10. Button(this.changeAppear)
  11. .onClick(() => {
  12. this.isShow = !this.isShow
  13. }).margin(15)
  14. if(this.isShow) {
  15. Text(this.myText).fontSize(26).fontWeight(FontWeight.Bold)
  16. .onAppear(() => {
  17. promptAction.showToast({
  18. message: '展示这个文本',
  19. duration: 2000
  20. })
  21. })
  22. .onDisAppear(() => {
  23. promptAction.showToast({
  24. message: '隐藏这个文本',
  25. duration: 2000
  26. })
  27. })
  28. }
  29. }.width('100%').padding(30)
  30. }
  31. }

1.4、拖拽事件

拖拽事件指组件被长按后拖拽时触发的事件

onDragStart(event:(event?:DragEvent,extraParams?:string) => CustomBuilder | DragItemInfo)

第一次拖拽此事件绑定的组件时,触发回调

event:拖拽事件信息,包括拖拽点坐标

extraParams:拖拽事件额外信息

返回值用来显示拖拽时的提示组件

不支持冒泡

onDragEnter(event:(event?:DragEvent,extraParams?:string) => void)

拖拽进入组件范围时触发回调

event:拖拽事件信息,包括拖拽点坐标

extraParams:拖拽事件额外信息

当监听onDrop事件时,此事件才有效

不支持冒泡

onDragMove(event:(event?:DragEvent,extraParams?:string) => void)

拖拽在组件范围内移动时,触发回调

event:拖拽事件信息,包括拖拽点坐标

extraParams:拖拽事件额外信息

当监听了onDrop事件时,此事件才有效

不支持冒泡

onDragLeave(event:(event?:DragEvent,extraParams?:string) => void)

拖拽离开组件范围内时,触发回调

event:拖拽事件信息,包括拖拽点坐标

extraParams:拖拽事件额外信息

当监听了onDrop事件时,此事件才有效

不支持冒泡

onDrop(event:(event?:DragEvent,extraParams?:string) => void)

绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调

event:拖拽事件信息,包括拖拽点坐标

extraParams:拖拽事件额外信息

不支持冒泡

DragItemInfo说明

名称类型描述
pixelMapPixelMap

非必填

设置拖拽过程中显示的图片

builderCustomBuilder

非必填

拖拽过程中显示自定义组件

如果设置了pixelMap则忽略此值

extraInfostring拖拽项的描述

extraParams说明

拖拽事件额外信息,它是Json对象转换的string字符串,可通过Json.parse转换为Json对象获取如下属性

名称类型描述
selectedIndexnumber

当拖拽事件设在父容器的子元素时,selectedIndex表示当前被拖拽子元素是父容器第selectedIndex个子元素,selectedIndex从0开始。仅在ListItem组件的拖拽事件中生效

insertIndexnumber

当前拖拽元素在List组件中放下时,insertIndex表示被拖拽元素插入该组件的第insertIndex个位置,insertIndex从0开始。仅在List组件的拖拽事件中生效

DragEvent说明

名称类型描述
getX()number当前拖拽点相对于屏幕左上角的x轴坐标,单位为vp
getY()number当前拖拽点相对于屏幕左上角的y轴坐标,单位为vp

  1. @Observed
  2. class ClassA {
  3. public name: string
  4. public bol: boolean
  5. constructor(name:string,bol:boolean) {
  6. this.name = name
  7. this.bol = bol
  8. }
  9. }
  10. @Extend(Text) function textStyle(){
  11. .width('25%')
  12. .height(35)
  13. .fontSize(16)
  14. .textAlign(TextAlign.Center)
  15. .backgroundColor('#1d953f')
  16. }
  17. @Component
  18. struct Child {
  19. @ObjectLink a: ClassA
  20. @Builder pixelMapBuilder() {
  21. Column() {
  22. Text(this.a.name)
  23. .width('50%')
  24. .height(60)
  25. .fontSize(16)
  26. .borderRadius(10)
  27. .textAlign(TextAlign.Center)
  28. .backgroundColor(Color.Yellow)
  29. }
  30. }
  31. build(){
  32. Column(){
  33. Text(this.a.name)
  34. .textStyle()
  35. .visibility(this.a.bol ? Visibility.Visible : Visibility.None)
  36. .onDragStart(() => {
  37. this.a.bol = false
  38. return this.pixelMapBuilder()
  39. })
  40. .onTouch((event: TouchEvent) => {
  41. if(event.type === TouchType.Up) {
  42. this.a.bol = true
  43. }
  44. })
  45. Text('')
  46. .width('25%')
  47. .height(35)
  48. .fontSize(16)
  49. .textAlign(TextAlign.Center)
  50. .border({width:5, color: 'red'})
  51. .visibility(!this.a.bol ? Visibility.Visible : Visibility.None)
  52. }
  53. }
  54. }
  55. @Entry
  56. @Component
  57. struct DragTest {
  58. @State arr: ClassA[] = [new ClassA('A',true),new ClassA('B',true),new ClassA('C',true)]
  59. @State dragIndex: number = 0
  60. changeIndex(index1: number, index2:number) {
  61. // 交换数组位置
  62. [this.arr[index1],this.arr[index2]] = [this.arr[index2],this.arr[index1]];
  63. }
  64. build() {
  65. Column() {
  66. Row({space:15}) {
  67. List({space:20}) {
  68. ForEach(this.arr,(item,index) => {
  69. ListItem() {
  70. Column(){
  71. Child({a: this.arr[index]})
  72. }
  73. .onTouch((event:TouchEvent) => {
  74. if(event.type === TouchType.Down){
  75. this.dragIndex = index; // 当前拖拽的组件
  76. }
  77. })
  78. }
  79. })
  80. }
  81. .listDirection(Axis.Horizontal)
  82. .onDrop((event:DragEvent,extraParams:string) => {
  83. let js = JSON.parse(extraParams);
  84. this.changeIndex(this.dragIndex,js.insertIndex)
  85. })
  86. }
  87. .padding({top:10, bottom:10}).margin(10)
  88. }
  89. .width('100%').height('100%').padding({top:20}).margin({top:20})
  90. }
  91. }

1.5、按键事件

按键事件指组件与键盘、遥控器等按键设备交互时触发的事件,适用于所有可获焦组件。对于Text,Image等默认不可获焦的组件,可以设置focusable属性为true后使用按键事件。

onKeyEvent(event:(event?:KeyEvent) => void)

绑定该方法的组件获焦后,按键动作触发该回调

支持冒泡

KeyEvent对象说明

名称类型

描述

type

KeyType

按键的类型。

keyCode

number

按键的键码。

keyText

string

按键的键值。

keySource

KeySource

触发当前按键的输入设备类型。

deviceId

number

触发当前按键的输入设备ID。

metaKey

number

按键发生时元键(即Windows键盘的WIN键、Mac键盘的Command键)的状态,1表示按压态,0表示未按压态。

timestamp

number

事件时间戳。触发事件时距离系统启动的时间间隔,单位纳秒。

stopPropagation

() => void

阻塞事件冒泡传递。

  1. @Entry
  2. @Component
  3. struct KeyEventTest {
  4. @State text: string = ''
  5. @State eventType: string = ''
  6. build() {
  7. Column() {
  8. Button('keyEvent')
  9. .onKeyEvent((event:KeyEvent) =>{
  10. if(event.type === KeyType.Down) {
  11. this.eventType = 'Down'
  12. }
  13. if(event.type === KeyType.Up) {
  14. this.eventType = 'Up'
  15. }
  16. this.text = 'KeyType:' + this.eventType + '\n keyCode:' + event.keyCode
  17. + '\nkeyText:' + event.keyText
  18. })
  19. Text(this.text).padding(15)
  20. }
  21. .height(300).width('100%').padding(35)
  22. }
  23. }

1.6、焦点事件

焦点事件指页面焦点在可获焦组件间移动时触发的事件,组件可使用焦点事件来处理相关逻辑。

onFocus(event:() => void)

当前组件获取焦点时触发回调

不支持冒泡

onBlur(event:() => void)

当前组件失去焦点时触发的回调

不支持冒泡

  1. @Entry
  2. @Component
  3. struct FocusTest {
  4. @State oneButtonColor: string = '#FFC0CB'
  5. @State twoButtonColor: string = '#87CEFA'
  6. @State threeButtonColor: string = '#90EE90'
  7. build() {
  8. Column({space: 20}) {
  9. Button('按钮一')
  10. .backgroundColor(this.oneButtonColor)
  11. .width(260).height(60).fontColor(Color.Black)
  12. .focusable(true) // 使用组件可以获得焦点
  13. .onFocus(() => {
  14. this.oneButtonColor = '#FF0000'
  15. })
  16. .onBlur(() => {
  17. this.oneButtonColor = '#FFC0CB'
  18. })
  19. Button('按钮二')
  20. .backgroundColor(this.twoButtonColor)
  21. .width(260).height(60).fontColor(Color.Black)
  22. .focusable(true) // 使用组件可以获得焦点
  23. .onFocus(() => {
  24. this.twoButtonColor = '#FF0000'
  25. })
  26. .onBlur(() => {
  27. this.twoButtonColor = '#87CEFA'
  28. })
  29. Button('按钮三')
  30. .backgroundColor(this.threeButtonColor)
  31. .width(260).height(60).fontColor(Color.Black)
  32. .focusable(true) // 使用组件可以获得焦点
  33. .onFocus(() => {
  34. this.threeButtonColor = '#FF0000'
  35. })
  36. .onBlur(() => {
  37. this.threeButtonColor = '#90EE90'
  38. })
  39. }
  40. .width('100%').margin({top: 20})
  41. }
  42. }

1.7、鼠标事件

在鼠标的单个动作触发多个事件时,事件的顺序是固定的,鼠标事件默认透传。

onHover(event:(isHover?:boolean) => void)

鼠标进入或退出组件时触发该回调

isHover:表示鼠标是否悬浮在组件之上,鼠标进入时为true,退出时为false

不支持冒泡

onMouse(event:(event?:MouseEvent) => void)

当前组件被鼠标按键点击时或者鼠标在组件上悬浮移动时,触发该回调

event返回值包含触发事件时的时间戳、鼠标按键、动作、鼠标位置在整个屏幕上的坐标和相对于当前组件的坐标

MouseEvent对象说明

名称属性类型描述
screenXnumber鼠标位置相对于应用窗口左上角的x轴坐标
screenYnumber鼠标位置相对于应用窗口左上角的y轴坐标
xnumber鼠标位置相对于当前组件左上角的x轴坐标
ynumber鼠标位置相对于当前组件左上角的x轴坐标
buttonMouseButton鼠标按键
actionMouseAction鼠标动作
stopPropagation() => void阻塞事件冒泡
timestampnumber事件时间戳,单位纳秒,触发时间到距离系统启动时间间隔
targetEventTarget触发事件的元素对象显示区域
sourceSourceType事件输入设备

  1. @Entry
  2. @Component
  3. struct MouseEventTest {
  4. @State hoverText: string = 'no hover'
  5. @State mouseText: string = ''
  6. @State action: string = ''
  7. @State mouseBtn: string = ''
  8. @State color: Color = Color.Blue
  9. build() {
  10. Column({space: 20}){
  11. Button(this.hoverText)
  12. .width(180).height(80)
  13. .backgroundColor(this.color)
  14. .onHover((isHover: boolean) => {
  15. // 通过onHover来动态修改按钮文本的颜色
  16. if(isHover) {
  17. this.hoverText = 'hover'
  18. this.color = Color.Pink
  19. } else {
  20. this.hoverText = 'no hover'
  21. this.color = Color.Blue
  22. }
  23. })
  24. Button('onMouse')
  25. .width(180).height(80)
  26. .onMouse((event: MouseEvent) => {
  27. switch (event.button) {
  28. case MouseButton.None:
  29. this.mouseBtn = 'None';
  30. break;
  31. case MouseButton.Left:
  32. this.mouseBtn = 'Left';
  33. break;
  34. case MouseButton.Right:
  35. this.mouseBtn = 'Right';
  36. break;
  37. case MouseButton.Back:
  38. this.mouseBtn = 'Back';
  39. break;
  40. case MouseButton.Forward:
  41. this.mouseBtn = 'Forward';
  42. break;
  43. case MouseButton.Middle:
  44. this.mouseBtn = 'Middle';
  45. break;
  46. default:
  47. break;
  48. }
  49. switch (event.action) {
  50. case MouseAction.Hover:
  51. this.action = 'Hover'
  52. break;
  53. case MouseAction.Press:
  54. this.action = 'Press'
  55. break;
  56. case MouseAction.Release:
  57. this.action = 'Release'
  58. break;
  59. default:
  60. break;
  61. }
  62. this.mouseText = 'onMouse:\nButton = ' + this.mouseBtn +
  63. '\nAction = ' + this.action + '\nXY=(' + event.x + ',' + event.y + ')' +
  64. '\nscreenXY=(' + event.screenX + ',' + event.screenY + ')';
  65. })
  66. Text(this.mouseText)
  67. }
  68. .padding({top:30}).width('100%')
  69. }
  70. }

1.8、组件区域变化事件

组件区域变化事件指组件显示的尺寸、位置等发生变化时触发的事件

onAreaChange(event:(oldValue:Area,newValue:Area) => void)

组件区域变化时触发该回调。仅会响应由布局变化所导致的组件大小、位置发生变化时的回调,由绘制变化所导致的渲染属性变化不会响应回调。比如说translate、offset不会响应

Area:目标元素的宽高以及目标元素相对父元素和页面左上角的坐标位置

  1. @Entry
  2. @Component
  3. struct AreaTest {
  4. @State value: string = 'Text'
  5. @State sizeValue: string = ''
  6. build() {
  7. Column() {
  8. Text(this.value)
  9. .backgroundColor(Color.Green).margin(30).fontSize(20)
  10. .onClick(() => {
  11. this.value = this.value + 'Text'
  12. })
  13. .onAreaChange((oldValue: Area, newValue: Area) => {
  14. this.sizeValue = JSON.stringify(newValue)
  15. })
  16. Text('new area is: \n' + this.sizeValue).margin({right: 30, left: 30})
  17. }
  18. .width('100%').height('100%').margin({top: 30})
  19. }
  20. }

1.9、组件可见区域变化事件

组件可见区域变化事件是组件在屏幕中的显示区域面积变化时触发的事件,提供了判断组件是否完全或部分显示在屏幕中的能力,适用于广告曝光埋点之类的场景。

onVisibleAreaChange(ratios:Array<number>,event:(isVisible:boolean,currentRatio:number) => void)

组件可见区域变化时触发该回调

ratos: 阀值数组,每个阈值代表组件可见面积与组件自身面积的比值。当组件可见面积与自身面积的比值大于或小于阈值时,均会触发该回调

阀值的取值范围:[0.0,1.0]

isVisible:示组件的可见面积与自身面积的比值是否大于阈值,true表示大于,false表示小于

currentRatio:触发回调时,组件可见面积与自身面积的比值

注意:该接口只适用于组件布局区域超出或离开了当前屏幕显示区域的情况,不支持组件堆叠(Stack)导致的面积不可见、使用offset或translate等图形变换接口导致的面积超出情况

  1. @Entry
  2. @Component
  3. struct VisibleAreaTest {
  4. scroller: Scroller = new Scroller()
  5. private arr: number[] = [0,1,2,3,4,5,6,7,8,9]
  6. @State testTextStr: string = 'test'
  7. @State testRowStr: string = 'test'
  8. build() {
  9. Column(){
  10. Column(){
  11. Text(this.testTextStr)
  12. .fontSize(20)
  13. Text(this.testRowStr)
  14. .fontSize(20)
  15. }
  16. .height(100)
  17. .backgroundColor(Color.Gray)
  18. .opacity(0.3)
  19. Scroll(this.scroller) {
  20. Column(){
  21. Text('Test Text Visible Change')
  22. .fontSize(20)
  23. .height(200)
  24. .margin({top: 50, bottom: 20})
  25. .backgroundColor(Color.Green)
  26. // ratios设置为[0.0,1.0]表示完全显示或完全消失时触发回调
  27. .onVisibleAreaChange([0.0,1.0],(isVisible: boolean,currentRatio: number) => {
  28. if(isVisible && currentRatio >= 1.0) {
  29. this.testTextStr = 'Test Text 完全显示'
  30. }
  31. if(!isVisible && currentRatio <= 0.0) {
  32. this.testTextStr = 'Test Text 完全消失'
  33. }
  34. })
  35. Row() {
  36. Text('Test Row Visible Change')
  37. .fontSize(20)
  38. .margin({bottom: 20})
  39. }
  40. .height(200)
  41. .backgroundColor(Color.Yellow)
  42. .onVisibleAreaChange([0.0,1.0],(isVisible:boolean,currentRatio:number) => {
  43. if (isVisible && currentRatio >= 1.0) {
  44. this.testRowStr = 'Test Row 完全显示'
  45. }
  46. if (!isVisible && currentRatio <= 0.0) {
  47. this.testRowStr = 'Test Row 完全消失'
  48. }
  49. })
  50. ForEach(this.arr, (item) => {
  51. Text(item.toString())
  52. .width('90%')
  53. .height(150)
  54. .backgroundColor(0xFFFFFF)
  55. .borderRadius(15)
  56. .textAlign(TextAlign.Center)
  57. .margin({top:10})
  58. },item => item)
  59. }
  60. .width('100%')
  61. }
  62. .backgroundColor(0x317aff)
  63. .scrollable(ScrollDirection.Vertical)
  64. .scrollBar(BarState.On)
  65. .scrollBarColor(Color.Gray)
  66. .scrollBarWidth(10)
  67. .onScroll((xOffset: number, yOffset: number) => {
  68. console.info(xOffset + ' ' + yOffset)
  69. })
  70. .onScrollEdge((side: Edge) => {
  71. })
  72. .onScrollEnd(() => {
  73. })
  74. }.width('100%').height('100%').backgroundColor(0xDCDCDC)
  75. }
  76. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/350293
推荐阅读
相关标签
  

闽ICP备14008679号