• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Touchscreen Event
2
3
4Touchscreen events are events triggered when a finger or stylus is placed on, moved along, or lifted from a component. They can be classified as [click event](#click-event), [drag event](#drag-event), or [touch event](#touch-event).
5
6
7**Figure 1** Touchscreen event principles
8
9
10![en-us_image_0000001562700461](figures/en-us_image_0000001562700461.png)
11
12
13## Click Event
14
15A click event is triggered when a complete press and lift action is performed by using a finger or a stylus. When a click event occurs, the following callback is triggered:
16
17
18
19```ts
20onClick(event: (event?: ClickEvent) => void)
21```
22
23
24The **event** parameter provides the coordinates of the click relative to the window or component as well as the event source where the click occurs, for example, a button, a click on which shows or hides an image.
25
26```ts
27@Entry
28@Component
29struct IfElseTransition {
30  @State flag: boolean = true;
31  @State btnMsg: string = 'show';
32
33  build() {
34    Column() {
35      Button(this.btnMsg).width(80).height(30).margin(30)
36        .onClick(() => {
37          if (this.flag) {
38            this.btnMsg = 'hide';
39          } else {
40            this.btnMsg = 'show';
41          }
42          // Click the button to show or hide the image.
43          this.flag = !this.flag;
44        })
45      if (this.flag) {
46        Image($r('app.media.icon')).width(200).height(200)
47      }
48    }.height('100%').width('100%')
49  }
50}
51```
52
53
54## Drag Event
55
56A drag event is triggered when a user long presses a component (>= 500 ms) using a finger or stylus and drags the component to the drop target.
57
58Whether a drag event can be triggered depends on the distance of finger or stylus movement on the screen. The drag event is triggered when this distance reaches 5 vp. ArkUI supports intra-application and cross-application drag events.
59
60The following figure illustrates the process of triggering a drag event.
61
62
63![en-us_image_0000001562820825](figures/en-us_image_0000001562820825.png)
64
65
66The drag event provides the following [APIs](../reference/arkui-ts/ts-universal-events-drag-drop.md).
67
68
69| API                                    | Description                                      |
70| ---------------------------------------- | ---------------------------------------- |
71| onDragStart(event: (event?: DragEvent, extraParams?: string) => CustomBuilder \| DragItemInfo) | Triggered when dragging starts. Currently, only custom **pixelmap** objects and custom components are supported.          |
72| onDragEnter(event: (event?: DragEvent, extraParams?: string) =&gt; void) | Triggered when the dragged item enters a valid drop target. **DragEvent**: position where the drag occurs.<br>**extraParmas**: custom information about the drag event.|
73| onDragLeave(event: (event?: DragEvent, extraParams?: string) =&gt; void) | Triggered when the dragged item leaves a valid drop target. **DragEvent**: position where the drag occurs.<br>**extraParmas**: custom information about the drag event.|
74| onDragMove(event: (event?: DragEvent, extraParams?: string) =&gt; void) | Triggered when the dragged item moves in a valid drop target. **DragEvent**: position where the drag occurs.<br>**extraParmas**: custom information about the drag event.|
75| onDrop(event: (event?: DragEvent, extraParams?: string) =&gt; void) | Triggered when the dragged item is dropped on a valid drop target. **DragEvent**: position where the drag occurs.<br>**extraParmas**: custom information about the drag event.|
76
77
78The following is an example of dragging a component out of a window in cross-window dragging:
79
80
81
82```ts
83import image from '@ohos.multimedia.image';
84
85@Entry
86@Component
87struct Index {
88  @State visible: Visibility = Visibility.Visible
89  private pixelMapReader:image.PixelMap|undefined = undefined
90
91  aboutToAppear() {
92    console.info('begin to create pixmap has info message: ')
93    this.createPixelMap()
94  }
95
96  createPixelMap() {
97    let color = new ArrayBuffer(4 * 96 * 96);
98    let buffer = new Uint8Array(color);
99    for (let i = 0; i < buffer.length; i++) {
100      buffer[i] = (i + 1) % 255;
101    }
102    class hw{
103      height:number = 96
104      width:number = 96
105    }
106    let hwo:hw = new hw()
107    let ops:image.InitializationOptions|void = {
108      'alphaType': 0,
109      'editable': true,
110      'pixelFormat': 4,
111      'scaleMode': 1,
112      'size': hwo
113    }
114    const promise: Promise<image.PixelMap> = image.createPixelMap(color, ops);
115    promise.then((data:image.PixelMap|undefined) => {
116      console.info('create pixmap has info message: ' + JSON.stringify(data))
117      if(data){
118        this.pixelMapReader = data;
119      }
120    })
121  }
122
123  @Builder pixelMapBuilder() {
124    Text('drag item')
125      .width('100%')
126      .height(100)
127      .fontSize(16)
128      .textAlign(TextAlign.Center)
129      .borderRadius(10)
130      .backgroundColor(0xFFFFFF)
131  }
132
133  build() {
134    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
135      Text('App1')
136        .width('40%')
137        .height(80)
138        .fontSize(20)
139        .margin(30)
140        .textAlign(TextAlign.Center)
141        .backgroundColor(Color.Pink)
142        .visibility(Visibility.Visible)
143
144      Text('Across Window Drag This')
145        .width('80%')
146        .height(80)
147        .fontSize(16)
148        .margin(30)
149        .textAlign(TextAlign.Center)
150        .backgroundColor(Color.Pink)
151        .visibility(this.visible)
152        .onDragStart((event: DragEvent|undefined, extraParams: string|undefined):CustomBuilder | DragItemInfo => {
153          console.info('Text onDrag start')
154          return { pixelMap: this.pixelMapReader, extraInfo: 'custom extra info.' }
155        })
156        .onDrop((event: DragEvent|undefined, extraParams: string|undefined) => {
157          console.info('Text onDragDrop,  ')
158          this.visible = Visibility.None                    // Make the source invisible after the dragging is complete.
159        })
160    }
161
162    .width('100%')
163    .height('100%')
164  }
165}
166```
167
168
169The following is an example of dragging a component into a window in cross-window dragging:
170
171
172
173```ts
174
175@Entry
176@Component
177struct Index {
178  @State number: string[] = ['drag here']
179  @State text: string = ''
180  @State bool1: boolean = false
181  @State bool2: boolean = false
182  @State visible: Visibility = Visibility.Visible
183  @State visible2: Visibility = Visibility.None
184  scroller: Scroller = new Scroller()
185
186  build() {
187    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
188      Text('App2')
189        .width('40%')
190        .height(80)
191        .fontSize(20)
192        .margin(30)
193        .textAlign(TextAlign.Center)
194        .backgroundColor(Color.Pink)
195        .visibility(Visibility.Visible)
196
197      List({ space: 20, initialIndex: 0 }) {
198        ForEach(this.number, (item:string) => {
199          ListItem() {
200            Text('' + item)
201              .width('100%')
202              .height(80)
203              .fontSize(16)
204              .borderRadius(10)
205              .textAlign(TextAlign.Center)
206              .backgroundColor(0xFFFFFF)
207          }
208        }, (item:string):string => item)
209
210        ListItem() {
211          Text('Across Window Drag This')
212            .width('80%')
213            .height(80)
214            .fontSize(16)
215            .margin(30)
216            .textAlign(TextAlign.Center)
217            .backgroundColor(Color.Pink)
218            .visibility(this.visible2)
219        }
220      }
221      .height('50%')
222      .width('90%')
223      .border({ width: 1 })
224      .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 })
225      .onDragEnter((event: DragEvent|undefined, extraParams: string|undefined) => {                         // Triggered when the dragged item enters a valid drop target.
226        console.info('List onDragEnter, ' + extraParams)
227      })
228      .onDragMove((event: DragEvent|undefined, extraParams: string|undefined) => {                          // Triggered when the dragged item moves in a valid drop target.
229        console.info('List onDragMove, ' + extraParams)
230      })
231      .onDragLeave((event: DragEvent|undefined, extraParams: string|undefined) => {                         // Triggered when the dragged item leaves a valid drop target.
232        console.info('List onDragLeave, ' + extraParams)
233      })
234      .onDrop((event: DragEvent|undefined, extraParams: string|undefined) => {                              // Triggered when the dragged item is dropped on a valid drop target.
235        console.info('List onDragDrop, ' + extraParams)
236        this.visible2 = Visibility.Visible                                              // Make the dragged object visible.
237      })
238    }
239    .width('100%')
240    .height('100%')
241  }
242}
243```
244
245
246## Touch Event
247
248A touch event is triggered when a finger or stylus is placed on, moved along, or lifted from a component.
249
250
251```ts
252onTouch(event: (event?: TouchEvent) => void)
253```
254
255- If **event.type** is **TouchType.Down**, the finger or stylus is placed on the component.
256
257- If **event.type** is **TouchType.Up**, the finger or stylus is lifted from the component.
258
259- If **event.type** is **TouchType.Move**, the finger or stylus is moved along the component.
260
261The touch event supports single and multi-touch interactions. Information about the touch event can be obtained using the **event** parameter, such as the location of the finger that triggers the event, unique identifier of the finger, finger information changed, and the input device source.
262
263
264```ts
265// xxx.ets
266@Entry
267@Component
268struct TouchExample {
269  @State text: string = '';
270  @State eventType: string = '';
271
272  build() {
273    Column() {
274      Button('Touch').height(40).width(100)
275        .onTouch((event?: TouchEvent) => {
276          if(event){
277            if (event.type === TouchType.Down) {
278              this.eventType = 'Down';
279            }
280            if (event.type === TouchType.Up) {
281              this.eventType = 'Up';
282            }
283            if (event.type === TouchType.Move) {
284              this.eventType = 'Move';
285            }
286            this.text = 'TouchType:' + this.eventType + '\nDistance between touch point and touch element:\nx: '
287            + event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:('
288            + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:'
289            + event.target.area.width + '\nheight:' + event.target.area.height
290          }
291        })
292      Button('Touch').height(50).width(200).margin(20)
293        .onTouch((event?: TouchEvent) => {
294          if(event){
295            if (event.type === TouchType.Down) {
296              this.eventType = 'Down';
297            }
298            if (event.type === TouchType.Up) {
299              this.eventType = 'Up';
300            }
301            if (event.type === TouchType.Move) {
302              this.eventType = 'Move';
303            }
304            this.text = 'TouchType:' + this.eventType + '\nDistance between touch point and touch element:\nx: '
305            + event.touches[0].x + '\n' + 'y: ' + event.touches[0].y + '\nComponent globalPos:('
306            + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:'
307            + event.target.area.width + '\nheight:' + event.target.area.height
308          }
309        })
310      Text(this.text)
311    }.width('100%').padding(30)
312  }
313}
314```
315
316
317![en-us_image_0000001511900468](figures/en-us_image_0000001511900468.gif)
318