• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Drag Event
2
3A drag event is triggered when a component is dragged.
4
5>  **NOTE**
6>
7>  The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
8
9## Events
10
11| Name                                                        | Bubbling Supported| Description                                                    |
12| ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
13| onDragStart(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt;  [CustomBuilder](ts-types.md#custombuilder8) \| [DragItemInfo](#dragiteminfo)) | No      | Triggered when the component bound to the event is dragged for the first time.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>Return value: object being dragged, which is used for prompts displayed when the object is dragged.<br>A drag event can be triggered by a 150 ms long press. If the duration of a long-press gesture is set to less than or equal to 150 ms, the callback for the long-press gesture takes precedence. Otherwise, the callback for the drag event takes precedence. |
14| onDragEnter(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No      | Triggered when the dragged item enters a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when a listener for the **onDrop** event is enabled.|
15| onDragMove(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No      | Triggered when the dragged item moves in a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when a listener for the **onDrop** event is enabled.|
16| onDragLeave(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No      | Triggered when the dragged item leaves a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when a listener for the **onDrop** event is enabled.|
17| onDrop(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No      | Triggered when the dragged item is dropped on a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.|
18
19## DragItemInfo
20
21| Name     | Type                                    | Mandatory  | Description                               |
22| --------- | ---------------------------------------- | ---- | --------------------------------- |
23| pixelMap  | [PixelMap](../apis/js-apis-image.md#pixelmap7) | No   | Image to be displayed during dragging.                    |
24| builder   | [CustomBuilder](ts-types.md#custombuilder8) | No   | Custom component to display during dragging. If **pixelMap** is set, this attribute is ignored.|
25| extraInfo | string                                   | No   | Extra information of the dragged item.                          |
26
27
28## extraParams
29
30  Provides additional information required for dragging an item.
31
32  **extraParams** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**.
33
34| Name         | Type  | Description                                      |
35| ------------- | ------ | ---------------------------------------- |
36| selectedIndex | number | Index of the dragged item in the parent container. The value of **selectedindex** starts from **0**.<br>This attribute is valid only in the drag event of the **\<ListItem>** component.|
37| insertIndex   | number | Index of the element into which the dragged item is dropped in the **List** component. The value of **insertIndex** starts from **0**.<br>This attribute is valid only in the drag event of the **\<List>** component.|
38
39## DragEvent
40
41| Name    | Type | Description            |
42| ------ | ------ | ---------------- |
43| getX() | number | X-coordinate of the drag position relative to the upper left corner of the screen, in vp.|
44| getY() | number | Y-coordinate of the drag position relative to the upper left corner of the screen, in vp.|
45
46## Example
47
48```ts
49// xxx.ets
50@Extend(Text) function textStyle () {
51  .width('25%')
52  .height(35)
53  .fontSize(16)
54  .textAlign(TextAlign.Center)
55  .backgroundColor(0xAFEEEE)
56}
57
58@Entry
59@Component
60struct DragExample {
61  @State numbers: string[] = ['one', 'two', 'three', 'four', 'five', 'six']
62  @State text: string = ''
63  @State bool: boolean = true
64  @State eventType: string = ''
65  @State appleVisible: Visibility = Visibility.Visible
66  @State orangeVisible: Visibility = Visibility.Visible
67  @State bananaVisible: Visibility = Visibility.Visible
68  private dragList: string[] = ['apple', 'orange', 'banana']
69  @State fruitVisible: Visibility[] = [Visibility.Visible, Visibility.Visible, Visibility.Visible]
70  @State idx: number = 0
71
72  // Customize the content displayed during dragging.
73  @Builder pixelMapBuilder() {
74    Column() {
75      Text(this.text)
76        .width('50%')
77        .height(60)
78        .fontSize(16)
79        .borderRadius(10)
80        .textAlign(TextAlign.Center)
81        .backgroundColor(Color.Yellow)
82    }
83  }
84
85  build() {
86    Column() {
87      Text('There are three Text elements here')
88        .fontSize(12)
89        .fontColor(0xCCCCCC)
90        .width('90%')
91        .textAlign(TextAlign.Start)
92        .margin(5)
93      Row({ space: 15 }) {
94        ForEach(this.dragList, (item, index) => {
95          Text(item)
96            .textStyle()
97            .visibility(this.fruitVisible[index])
98            .onDragStart(() => {
99              this.bool = true
100              this.text = item
101              this.fruitVisible[index] = Visibility.None
102              return this.pixelMapBuilder
103            })
104            .onTouch((event: TouchEvent) => {
105              if (event.type === TouchType.Down) {
106                this.eventType = 'Down'
107                this.idx = index
108              }
109              if (event.type === TouchType.Up) {
110                this.eventType = 'Up'
111                if (this.bool) {
112                  this.fruitVisible[index] = Visibility.Visible
113                }
114              }
115            })
116        })
117      }.padding({ top: 10, bottom: 10 }).margin(10)
118
119      Text('This is a List element')
120        .fontSize(12)
121        .fontColor(0xCCCCCC)
122        .width('90%')
123        .textAlign(TextAlign.Start)
124        .margin(15)
125      List({ space: 20 }) {
126        ForEach(this.numbers, (item) => {
127          ListItem() {
128            Text(item)
129              .width('100%')
130              .height(80)
131              .fontSize(16)
132              .borderRadius(10)
133              .textAlign(TextAlign.Center)
134              .backgroundColor(0xAFEEEE)
135          }
136        }, item => item)
137      }
138      .editMode(true)
139      .height('50%')
140      .width('90%')
141      .border({ width: 1 })
142      .padding(15)
143      .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 })
144      .onDragEnter((event: DragEvent, extraParams: string) => {
145        console.log('List onDragEnter, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY())
146      })
147      .onDragMove((event: DragEvent, extraParams: string) => {
148        console.log('List onDragMove, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY())
149      })
150      .onDragLeave((event: DragEvent, extraParams: string) => {
151        console.log('List onDragLeave, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY())
152      })
153      .onDrop((event: DragEvent, extraParams: string) => {
154        let jsonString = JSON.parse(extraParams);
155        if (this.bool) {
156          // Insert an element using the splice method.
157          this.numbers.splice(jsonString.insertIndex, 0, this.text)
158          this.bool = false
159        }
160        this.fruitVisible[this.idx] = Visibility.None
161      })
162    }.width('100%').height('100%').padding({ top: 20 }).margin({ top: 20 })
163  }
164}
165```
166
167![en-us_image_0000001252667389](figures/en-us_image_0000001252667389.gif)
168