• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.arkui.dragController (DragController)
2
3本模块提供发起主动拖拽的能力,当应用接收到触摸或长按等事件时可以主动发起拖拽的动作,并在其中携带拖拽信息。
4
5> **说明:**
6>
7> 本模块首批接口从 API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8> 本模块功能依赖UI的执行上下文,不可在UI上下文不明确的地方使用,参见[UIContext](js-apis-arkui-UIContext.md#uicontext)说明。
9> 示例效果请以真机运行为准,当前 IDE 预览器不支持。
10
11## 导入模块
12
13```ts
14import { dragController } from "@kit.ArkUI";
15```
16
17## dragController.executeDrag<sup>(deprecated)</sup>
18
19executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: DragInfo,callback:AsyncCallback\<DragEventParam>): void
20
21主动发起拖拽能力,传入拖拽发起后跟手效果所拖拽的对象以及携带拖拽信息。通过回调返回结果。
22
23> **说明:**
24>
25> 从API version 18开始废弃,建议使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)获取[DragController](js-apis-arkui-UIContext.md#dragcontroller11)实例,再通过此实例调用替代方法[executeDrag](js-apis-arkui-UIContext.md#executedrag11)。
26>
27> 从API version 11开始,可以通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取当前UI上下文关联的[DragController](js-apis-arkui-UIContext.md#dragcontroller11)对象。
28
29**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
30
31**系统能力:** SystemCapability.ArkUI.ArkUI.Full
32
33**参数:**
34
35| 参数名   | 类型                                                         | 必填 | 说明                                                         |
36| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
37| custom   | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明) | 是   | 拖拽发起后跟手效果所拖拽的对象。<br/>**说明:** <br/>不支持全局builder。如果builder中使用了[Image](arkui-ts/ts-basic-components-image.md)组件,应尽量开启同步加载,即配置Image的[syncLoad](arkui-ts/ts-basic-components-image.md#syncload8)为true。该builder只用于生成当次拖拽中显示的图片,builder的修改不会同步到当前正在拖拽的图片,对builder的修改需要在下一次拖拽时生效。 |
38| dragInfo | [DragInfo](#draginfo)                                        | 是   | 拖拽信息。                                                   |
39| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;[DragEventParam](#drageventparam12)&gt; | 是   | 拖拽结束返回结果的回调。                                     |
40
41**错误码:**
42
43以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。
44
45| 错误码ID | 错误信息      |
46| -------- | ------------- |
47| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
48| 100001   | Internal handling failed. |
49
50**示例:**
51
52> **说明:**
53>
54> 推荐通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取当前UI上下文关联的DragController对象。
55
56```ts
57import { dragController } from "@kit.ArkUI";
58import { unifiedDataChannel } from '@kit.ArkData';
59
60@Entry
61@Component
62struct DragControllerPage {
63  @State text: string = ''
64
65  @Builder DraggingBuilder() {
66    Column() {
67      Text("DraggingBuilder")
68        .fontColor(Color.White)
69        .fontSize(12)
70    }
71    .width(100)
72    .height(100)
73    .backgroundColor(Color.Blue)
74  }
75
76  build() {
77    Column() {
78      Button('touch to execute drag')
79        .margin(10)
80        .onTouch((event?:TouchEvent) => {
81          if(event){
82            if (event.type == TouchType.Down) {
83              let text = new unifiedDataChannel.PlainText()
84              text.textContent = 'drag text'
85              text.abstract = 'abstract'
86              let unifiedData = new unifiedDataChannel.UnifiedData(text)
87
88              let dragInfo: dragController.DragInfo = {
89                pointerId: 0,
90                data: unifiedData,
91                extraParams: ''
92              }
93              class tmp{
94                event:DragEvent|undefined = undefined
95                extraParams:string = ''
96              }
97              let eve:tmp = new tmp()
98              this.getUIContext().getDragController().executeDrag(()=>{this.DraggingBuilder()}, dragInfo, (err, eve) => { // 建议使用 this.getUIContext().getDragController().executeDrag()接口
99                if(eve.event){
100                  if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) {
101                    // ...
102                  } else if (eve.event.getResult() == DragResult.DRAG_FAILED) {
103                    // ...
104                  }
105                }
106              })
107            }
108          }
109        })
110      Text(this.text)
111        .height(100)
112        .width(150)
113        .margin({top:20})
114        .border({color:Color.Black,width:1})
115        .onDrop((dragEvent?:DragEvent)=>{
116          if(dragEvent){
117            let records: Array<unifiedDataChannel.UnifiedRecord> = dragEvent.getData().getRecords();
118            let plainText: unifiedDataChannel.PlainText = records[0] as unifiedDataChannel.PlainText;
119            this.text = plainText.textContent;
120          }
121        })
122    }
123    .width('100%')
124    .height('100%')
125  }
126}
127```
128  ![zh-cn_executeDrag1](figures/executeDrag1.gif)
129## dragController.executeDrag<sup>(deprecated)</sup>
130
131executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: DragInfo): Promise\<DragEventParam>
132
133主动发起拖拽能力,传入拖拽发起后跟手效果所拖拽的对象以及携带拖拽信息。通过Promise返回结果。
134
135> **说明:**
136>
137> 从API version 18开始废弃,建议使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)获取[DragController](js-apis-arkui-UIContext.md#dragcontroller11)实例,再通过此实例调用替代方法[executeDrag](js-apis-arkui-UIContext.md#executedrag11-1)。
138>
139> 从API version 11开始,可以通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取当前UI上下文关联的[DragController](js-apis-arkui-UIContext.md#dragcontroller11)对象。
140
141**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
142
143**系统能力:** SystemCapability.ArkUI.ArkUI.Full
144
145**参数:**
146
147| 参数名   | 类型                                                         | 必填 | 说明                             |
148| -------- | ------------------------------------------------------------ | ---- | -------------------------------- |
149| custom   | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明) | 是   | 拖拽发起后跟手效果所拖拽的对象。 |
150| dragInfo | [DragInfo](#draginfo)                                        | 是   | 拖拽信息。                       |
151
152**返回值:**
153
154| 类型                                               | 说明                     |
155| -------------------------------------------------- | ------------------------ |
156| Promise&lt;[DragEventParam](#drageventparam12)&gt; | 拖拽结束返回结果的回调。 |
157
158**错误码:**
159以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。
160| 错误码ID | 错误信息      |
161| -------- | ------------- |
162| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
163| 100001   | Internal handling failed. |
164
165**示例:**
166
167> **说明:**
168>
169> 推荐通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取当前UI上下文关联的DragController对象。
170
171```ts
172import { dragController } from "@kit.ArkUI"
173import { image } from '@kit.ImageKit';
174import { unifiedDataChannel } from '@kit.ArkData';
175
176@Entry
177@Component
178struct DragControllerPage {
179  @State pixmap: image.PixelMap|undefined = undefined
180  @State text: string = ''
181
182  @Builder DraggingBuilder() {
183    Column() {
184      Text("DraggingBuilder")
185        .fontColor(Color.White)
186    }
187    .width(100)
188    .height(100)
189    .backgroundColor(Color.Blue)
190  }
191
192  @Builder PixmapBuilder() {
193    Column() {
194      Text("PixmapBuilder")
195        .fontColor(Color.White)
196        .fontSize(15)
197    }
198    .width(100)
199    .height(100)
200    .backgroundColor(Color.Blue)
201  }
202
203  aboutToAppear() {
204    let pb: CustomBuilder = (): void => {
205      this.PixmapBuilder()
206    }
207    this.getUIContext().getComponentSnapshot().createFromBuilder(pb).then((pix: image.PixelMap) => {
208      this.pixmap = pix;
209    })
210  }
211
212  build() {
213    Column() {
214      Button('touch to execute drag')
215        .margin(10)
216        .onTouch((event?:TouchEvent) => {
217          if(event){
218            if (event.type == TouchType.Down) {
219              let text = new unifiedDataChannel.PlainText()
220              text.textContent = 'drag text'
221              text.abstract = 'abstract'
222              let unifiedData = new unifiedDataChannel.UnifiedData(text)
223
224              let dragInfo: dragController.DragInfo = {
225                pointerId: 0,
226                data: unifiedData,
227                extraParams: ''
228              }
229              let dragItemInfo: DragItemInfo = {
230                pixelMap: this.pixmap,
231                builder: ()=>{this.DraggingBuilder()},
232                extraInfo: "DragItemInfoTest"
233              }
234
235              class tmp{
236                event:DragResult|undefined = undefined
237                extraParams:string = ''
238              }
239              let eve:tmp = new tmp()
240              this.getUIContext().getDragController().executeDrag(dragItemInfo, dragInfo) // 建议使用 this.getUIContext().getDragController().executeDrag()接口
241                .then((eve) => {
242                  if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) {
243                    // ...
244                  } else if (eve.event.getResult() == DragResult.DRAG_FAILED) {
245                    // ...
246                  }
247                })
248                .catch((err:Error) => {
249                })
250            }
251          }
252        })
253      Text(this.text)
254        .height(100)
255        .width(150)
256        .margin({top:20})
257        .border({color:Color.Black,width:1})
258        .onDrop((dragEvent?:DragEvent)=>{
259          if(dragEvent){
260            let records: Array<unifiedDataChannel.UnifiedRecord> = dragEvent.getData().getRecords();
261            let plainText: unifiedDataChannel.PlainText = records[0] as unifiedDataChannel.PlainText;
262            this.text = plainText.textContent;
263          }
264        })
265    }
266    .width('100%')
267    .height('100%')
268  }
269}
270```
271  ![zh-cn_executeDrag2](figures/executeDrag2.gif)
272## DragInfo
273
274**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
275
276**系统能力:** SystemCapability.ArkUI.ArkUI.Full
277
278发起拖拽所需要的属性和拖拽时携带的信息。
279
280| 名称        | 类型                                                   | 必填 | 说明                                     |
281| ----------- | ------------------------------------------------------ | ---- | ---------------------------------------- |
282| pointerId   | number                                                 | 是   | 设置启动拖拽时屏幕上触摸点的Id。取值范围为0-9的整数。         |
283| data        | [unifiedDataChannel.UnifiedData](../apis-arkdata/js-apis-data-unifiedDataChannel.md#unifieddata) | 否   | 设置拖拽过程中携带的数据。               |
284| extraParams | string                                                 | 否   | 设置拖拽事件额外信息,具体功能暂未实现。默认值为空。 |
285| touchPoint<sup>11+</sup>    | [TouchPoint](arkui-ts/ts-types.md#touchpoint11)  | 否   | 配置跟手点坐标。不配置时,左右居中,顶部向下偏移20%。 |
286| previewOptions<sup>11+</sup>| [DragPreviewOptions](arkui-ts/ts-universal-attributes-drag-drop.md#dragpreviewoptions11)                                | 否   | 设置拖拽过程中背板图处理模式及数量角标的显示。 |
287
288## dragController.createDragAction<sup>(deprecated)</sup>
289
290createDragAction(customArray: Array&lt;CustomBuilder \| DragItemInfo&gt;, dragInfo: DragInfo): DragAction
291
292创建拖拽的Action对象,需要显式指定拖拽背板图(可多个),以及拖拽的数据,跟手点等信息;当通过一个已创建的 Action 对象发起的拖拽未结束时,无法再次创建新的 Action 对象,接口会抛出异常;当Action对象的生命周期结束后,注册在该对象上的回调函数会失效,因此需要在一个尽量长的作用域下持有该对象,并在每次发起拖拽前通过createDragAction返回新的对象覆盖旧值。
293
294> **说明:**
295> 从API version 11开始支持,从API version 18开始废弃,建议使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)获取[DragController](js-apis-arkui-UIContext.md#dragcontroller11)实例,再通过此实例调用替代方法[createDragAction](js-apis-arkui-UIContext.md#createdragaction11)。
296>
297> 从API version 11开始,可以通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取当前UI上下文关联的[DragController](js-apis-arkui-UIContext.md#dragcontroller11)对象。
298>
299> 建议控制传递的拖拽背板数量,传递过多容易导致拖起的效率问题。
300
301**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
302
303**系统能力:** SystemCapability.ArkUI.ArkUI.Full
304
305**参数:**
306
307| 参数名   | 类型                                                         | 必填 | 说明                             |
308| --------      | ------------------------------------------------------------ | ---- | -------------------------------- |
309| customArray  | Array&lt;[CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明)&gt; | 是   | 拖拽发起后跟手效果所拖拽的对象。 |
310| dragInfo | [DragInfo](#draginfo)                                        | 是   | 拖拽信息。                       |
311
312**返回值:**
313
314| 类型                                                   | 说明               |
315| ------------------------------------------------------ | ------------------ |
316| [DragAction](#dragaction11)| 创建拖拽Action对象,主要用于后面实现注册监听拖拽状态改变事件和启动拖拽服务。 |
317
318**错误码:**
319
320以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。
321| 错误码ID | 错误信息      |
322| -------- | ------------- |
323| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
324| 100001   | Internal handling failed. |
325
326**示例:**
327
328> **说明:**
329>
330> 推荐通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取当前UI上下文关联的DragController对象。
331
332```ts
333import { dragController } from "@kit.ArkUI";
334import { image } from '@kit.ImageKit';
335import { unifiedDataChannel } from '@kit.ArkData';
336
337@Entry
338@Component
339struct DragControllerPage {
340  @State pixmap: image.PixelMap | null = null
341  @State text: string = ''
342  private dragAction: dragController.DragAction | null = null;
343  customBuilders:Array<CustomBuilder | DragItemInfo> = new Array<CustomBuilder | DragItemInfo>();
344  @Builder DraggingBuilder() {
345    Column() {
346      Text("DraggingBuilder")
347        .fontColor(Color.White)
348        .fontSize(12)
349    }
350    .width(100)
351    .height(100)
352    .backgroundColor(Color.Blue)
353  }
354
355  build() {
356    Column() {
357
358      Column() {
359        Text(this.text)
360          .width('100%')
361          .height('100%')
362          .fontColor(Color.White)
363          .fontSize(18)
364          .onDrop((dragEvent?:DragEvent)=>{
365            if(dragEvent){
366              let records: Array<unifiedDataChannel.UnifiedRecord> = dragEvent.getData().getRecords();
367              let plainText: unifiedDataChannel.PlainText = records[0] as unifiedDataChannel.PlainText;
368              this.text = plainText.textContent;
369            }
370          })
371      }
372      .width(100)
373      .height(100)
374      .backgroundColor(Color.Red)
375      .margin(10)
376
377      Button('多对象dragAction customBuilder拖拽').onTouch((event?:TouchEvent) => {
378        if(event){
379          if (event.type == TouchType.Down) {
380            console.info("muti drag Down by listener");
381            this.customBuilders.splice(0, this.customBuilders.length);
382            this.customBuilders.push(()=>{this.DraggingBuilder()});
383            this.customBuilders.push(()=>{this.DraggingBuilder()});
384            this.customBuilders.push(()=>{this.DraggingBuilder()});
385            let text = new unifiedDataChannel.PlainText()
386            text.textContent = 'drag text'
387            let unifiedData = new unifiedDataChannel.UnifiedData(text)
388            let dragInfo: dragController.DragInfo = {
389              pointerId: 0,
390              data: unifiedData,
391              extraParams: ''
392            }
393            try{
394              this.dragAction = this.getUIContext().getDragController().createDragAction(this.customBuilders, dragInfo) // 建议使用 this.getUIContext().getDragController().createDragAction()接口
395              if(!this.dragAction){
396                console.info("listener dragAction is null");
397                return
398              }
399              this.dragAction.on('statusChange', (dragAndDropInfo: dragController.DragAndDropInfo)=>{
400                if (dragAndDropInfo.status == dragController.DragStatus.STARTED) {
401                  console.info("drag has start");
402                } else if (dragAndDropInfo.status == dragController.DragStatus.ENDED){
403                  console.info("drag has end");
404                  if (!this.dragAction) {
405                    return
406                  }
407                  this.dragAction.off('statusChange')
408                }
409              })
410              this.dragAction.startDrag().then(()=>{}).catch((err:Error)=>{
411                console.info("start drag Error:" + err.message);
412              })
413            } catch(err) {
414              console.info("create dragAction Error:" + err.message);
415            }
416          }
417        }
418      }).margin({top:20})
419    }
420  }
421}
422```
423  ![zh-cn_executeDrag3](figures/executeDrag3.gif)
424## DragAction<sup>11+</sup>
425
426监听状态改变,启动拖拽服务的对象。
427
428**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
429
430**系统能力:** SystemCapability.ArkUI.ArkUI.Full
431
432### startDrag<sup>11+</sup>
433
434startDrag(): Promise&lt;void&gt;
435
436启动拖拽服务,返回Promise对象,回调启动成功和失败的结果。
437
438**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
439
440**系统能力:** SystemCapability.ArkUI.ArkUI.Full
441
442**错误码:**
443
444| 错误码ID | 错误信息      |
445| -------- | ------------- |
446| 100001   | Internal handling failed. |
447
448**示例:**
449
450> **说明:**
451>
452> 推荐通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取当前UI上下文关联的DragController对象。
453
454```ts
455import { dragController } from "@kit.ArkUI";
456import { unifiedDataChannel } from '@kit.ArkData';
457
458@Entry
459@Component
460struct DragControllerPage {
461  private dragAction: dragController.DragAction | null = null;
462  customBuilders:Array<CustomBuilder | DragItemInfo> = new Array<CustomBuilder | DragItemInfo>();
463  @Builder DraggingBuilder() {
464    Column() {
465      Text("DraggingBuilder")
466        .fontColor(Color.White)
467        .fontSize(12)
468    }
469    .width(100)
470    .height(100)
471    .backgroundColor(Color.Blue)
472  }
473
474  build() {
475    Column() {
476      Button('touch to execute drag').onTouch((event?:TouchEvent) => {
477        if(event){
478          if (event.type == TouchType.Down) {
479            this.customBuilders.splice(0, this.customBuilders.length);
480            this.customBuilders.push(()=>{this.DraggingBuilder()});
481            let text = new unifiedDataChannel.PlainText()
482            text.textContent = 'drag text'
483            let unifiedData = new unifiedDataChannel.UnifiedData(text)
484            let dragInfo: dragController.DragInfo = {
485              pointerId: 0,
486              data: unifiedData,
487              extraParams: ''
488            }
489            try{
490              this.dragAction = this.getUIContext().getDragController().createDragAction(this.customBuilders, dragInfo) // 建议使用 this.getUIContext().getDragController().createDragAction()接口
491              if(!this.dragAction){
492                console.info("listener dragAction is null");
493                return;
494              }
495              this.dragAction.startDrag().then(()=>{}).catch((err:Error)=>{
496                console.info("start drag Error:" + err.message);
497              })
498            } catch(err) {
499              console.info("create dragAction Error:" + err.message);
500            }
501          }
502        }
503      }).margin({top:20})
504    }
505  }
506}
507```
508
509### on('statusChange')<sup>11+</sup>
510
511on(type: 'statusChange', callback: Callback&lt;[DragAndDropInfo](#draganddropinfo11)&gt;): void
512
513注册监听拖拽状态改变事件。
514
515**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
516
517**系统能力:** SystemCapability.ArkUI.ArkUI.Full
518
519**参数:**
520| 参数名     | 类型  | 必填    | 说明             |
521| ------ | ------ | ------- | ---------------- |
522|  type  | string | 是      | 监听事件,固定为'statusChange',即注册监听拖拽状态改变事件。|
523|  callback  | Callback&lt;[DragAndDropInfo](#draganddropinfo11)&gt; | 是      | 回调函数,返回当前的[DragAndDropInfo](#draganddropinfo11)组件状态。|
524
525**示例:**
526
527> **说明:**
528>
529> 推荐通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取当前UI上下文关联的DragController对象。
530
531```ts
532import { dragController } from "@kit.ArkUI";
533import { unifiedDataChannel } from '@kit.ArkData';
534
535@Entry
536@Component
537struct DragControllerPage {
538  private dragAction: dragController.DragAction | null = null;
539  customBuilders:Array<CustomBuilder | DragItemInfo> = new Array<CustomBuilder | DragItemInfo>();
540  @Builder DraggingBuilder() {
541    Column() {
542      Text("DraggingBuilder")
543        .fontColor(Color.White)
544        .fontSize(12)
545    }
546    .width(100)
547    .height(100)
548    .backgroundColor(Color.Blue)
549  }
550
551  build() {
552    Column() {
553      Button('touch to execute drag').onTouch((event?:TouchEvent) => {
554        if(event){
555          if (event.type == TouchType.Down) {
556            this.customBuilders.splice(0, this.customBuilders.length);
557            this.customBuilders.push(()=>{this.DraggingBuilder()});
558            let text = new unifiedDataChannel.PlainText()
559            text.textContent = 'drag text'
560            let unifiedData = new unifiedDataChannel.UnifiedData(text)
561            let dragInfo: dragController.DragInfo = {
562              pointerId: 0,
563              data: unifiedData,
564              extraParams: ''
565            }
566            let func = (dragAndDropInfo: dragController.DragAndDropInfo) => {
567              console.info("Register to listen on drag status", JSON.stringify(dragAndDropInfo));
568            }
569            try{
570              this.dragAction = this.getUIContext().getDragController().createDragAction(this.customBuilders, dragInfo) // 建议使用 this.getUIContext().getDragController().createDragAction()接口
571              if(!this.dragAction){
572                console.info("listener dragAction is null");
573                return;
574              }
575              // 监听状态改变,触发后打印func中的日志
576              this.dragAction.on('statusChange', func);
577              this.dragAction.startDrag().then(()=>{}).catch((err:Error)=>{
578                console.info("start drag Error:" + err.message);
579              })
580            } catch(err) {
581              console.info("create dragAction Error:" + err.message);
582            }
583          }
584        }
585      }).margin({top:20})
586    }
587  }
588}
589```
590
591### off('statusChange')<sup>11+</sup>
592
593 off(type: 'statusChange', callback?: Callback&lt;[DragAndDropInfo](#draganddropinfo11)&gt;): void
594
595取消注册监听拖拽状态改变事件。
596
597**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
598
599**系统能力:** SystemCapability.ArkUI.ArkUI.Full
600
601**参数:**
602| 参数名     | 类型  | 必填    | 说明             |
603| ------ | ------ | ------- | ---------------- |
604|  type  | string | 是      | 监听事件,固定为'statusChange',即取消监听拖拽状态改变事件。|
605|  callback  | Callback&lt;[DragAndDropInfo](#draganddropinfo11)&gt; | 否      | 回调函数,取消注册了该回调函数的事件, 不设置取消所有监听。|
606
607**示例:**
608
609> **说明:**
610>
611> 推荐通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取当前UI上下文关联的DragController对象。
612
613```ts
614import { dragController } from "@kit.ArkUI";
615import { unifiedDataChannel } from '@kit.ArkData';
616
617@Entry
618@Component
619struct DragControllerPage {
620  private dragAction: dragController.DragAction | null = null;
621  customBuilders:Array<CustomBuilder | DragItemInfo> = new Array<CustomBuilder | DragItemInfo>();
622  @Builder DraggingBuilder() {
623    Column() {
624      Text("DraggingBuilder")
625        .fontColor(Color.White)
626        .fontSize(12)
627    }
628    .width(100)
629    .height(100)
630    .backgroundColor(Color.Blue)
631  }
632
633  build() {
634    Column() {
635      Button('touch to execute drag').onTouch((event?:TouchEvent) => {
636        if(event){
637          if (event.type == TouchType.Down) {
638            this.customBuilders.splice(0, this.customBuilders.length);
639            this.customBuilders.push(()=>{this.DraggingBuilder()});
640            let text = new unifiedDataChannel.PlainText()
641            text.textContent = 'drag text'
642            let unifiedData = new unifiedDataChannel.UnifiedData(text)
643            let dragInfo: dragController.DragInfo = {
644              pointerId: 0,
645              data: unifiedData,
646              extraParams: ''
647            }
648            let func = (dragAndDropInfo: dragController.DragAndDropInfo) => {
649              console.info("Register to listen on drag status", JSON.stringify(dragAndDropInfo));
650            }
651            try{
652              this.dragAction = this.getUIContext().getDragController().createDragAction(this.customBuilders, dragInfo) // 建议使用 this.getUIContext().getDragController().createDragAction()接口
653              if(!this.dragAction){
654                console.info("listener dragAction is null");
655                return;
656              }
657              this.dragAction.on('statusChange', func);
658              // 取消监听,发起拖拽后不会打印func中的日志
659              this.dragAction.off('statusChange', func);
660              this.dragAction.startDrag().then(()=>{}).catch((err:Error)=>{
661                console.info("start drag Error:" + err.message);
662              })
663            } catch(err) {
664              console.info("create dragAction Error:" + err.message);
665            }
666          }
667        }
668      }).margin({top:20})
669    }
670  }
671}
672```
673
674## DragAndDropInfo<sup>11+</sup>
675
676**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
677
678**系统能力:** SystemCapability.ArkUI.ArkUI.Full
679
680拖拽过程中监听到status改变时上报的数据。
681
682| 名称          | 类型                                                   | 必填 | 说明                                     |
683| -----------   | ------------------------------------------------------ | ---- | ---------------------------------------- |
684| status       | [DragStatus](#dragstatus11)                                                 | 是   | 当前拖拽状态(启动和结束)。         |
685| event        | [DragEvent](arkui-ts/ts-universal-events-drag-drop.md#dragevent) | 是   | 当前状态所对应的拖拽事件。通过dragController发起的dragEvent仅支持获取result和behavior,且用于拖拽结束状态。 |
686| extraParams| string                                                 | 否   | 设置拖拽事件额外信息,具体功能暂未实现。默认值为空。 |
687
688## DragStatus<sup>11+</sup>
689
690**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
691
692**系统能力:** SystemCapability.ArkUI.ArkUI.Full
693
694拖拽开始和结束状态。
695
696| 名称          | 值                                                   | 说明                                     |
697| -----------   | ------------------------------------------------------| ---------------------------------------- |
698| STARTED       | 0                                                  | 拖拽已成功发起。         |
699| ENDED        | 1                                                  | 拖拽结束。               |
700
701## AnimationOptions<sup>11+</sup>
702
703**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
704
705**系统能力:** SystemCapability.ArkUI.ArkUI.Full
706
707发起拖拽所需要的属性和拖拽时携带的信息。
708
709| 名称        | 类型                                                   | 必填 | 说明                                     |
710| ----------- | ------------------------------------------------------ | ---- | ---------------------------------------- |
711| duration    | number                                                 | 否   | 动画持续时间,单位为毫秒。<br/>默认值:1000<br/>**说明:**<br/>-&nbsp;设置小于0的值时按0处理。<br/>-&nbsp;设置浮点型类型的值时,向下取整。例如,设置值为1.2,按照1处理。|
712| curve       |&nbsp;[Curve](arkui-ts/ts-appendix-enums.md#curve)&nbsp;\|&nbsp;[ICurve](js-apis-curve.md#icurve) | 否    | 设置动画曲线。<br/>默认值:Curve.EaseInOut|                          |
713
714## DragEventParam<sup>12+</sup>
715
716**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
717
718**系统能力:** SystemCapability.ArkUI.ArkUI.Full
719
720拖拽结束返回结果的回调。
721
722| 名称        | 类型                                                         | 必填 | 说明                           |
723| ----------- | ------------------------------------------------------------ | ---- | ------------------------------ |
724| event       | [DragEvent](arkui-ts/ts-universal-events-drag-drop.md#dragevent) | 是   | 拖拽事件信息,仅包括拖拽结果。 |
725| extraParams | string                                                       | 是   | 拖拽事件额外信息。             |
726
727## dragController.getDragPreview<sup>(deprecated)</sup>
728
729getDragPreview(): DragPreview
730
731返回一个代表拖拽背板的对象。
732
733> **说明:**
734>
735> 从API version 11开始支持,从API version 18开始废弃,建议使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)获取[DragController](js-apis-arkui-UIContext.md#dragcontroller11)实例,再通过此实例调用替代方法[getDragPreview](js-apis-arkui-UIContext.md#getdragpreview11)。
736>
737> 从API version 11开始,可以通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取当前UI上下文关联的[DragController](js-apis-arkui-UIContext.md#dragcontroller11)对象。
738
739**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
740
741**系统能力:** SystemCapability.ArkUI.ArkUI.Full
742
743**返回值:**
744
745| 类型        | 说明                                            |
746| ------------| ------------------------------------------------|
747| [DragPreview](#dragpreview11) | 一个代表拖拽背板的对象,提供背板样式设置的接口,在OnDrop和OnDragEnd回调中使用不生效。 |
748
749**示例:**
750
751请参考[animate](#animate11)
752
753## DragPreview<sup>11+</sup>
754
755拖拽背板的对象,在OnDrop和OnDragEnd回调中使用不生效。
756
757**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
758
759**系统能力:** SystemCapability.ArkUI.ArkUI.Full
760
761### setForegroundColor<sup>11+</sup>
762
763setForegroundColor(color: ResourceColor): void
764
765设置背板蒙版颜色,在OnDrop和OnDragEnd回调中使用不生效,仅支持通过 [getDragPreview()](js-apis-arkui-UIContext.md#getdragpreview11) 方法获取到的对象上使用。
766
767**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
768
769**系统能力:** SystemCapability.ArkUI.ArkUI.Full
770
771**参数:**
772
773| 参数名   | 类型                             | 必填 | 说明                     |
774| -------- | -------------------------------- | ---- | ------------------------ |
775| color    | [ResourceColor](arkui-ts/ts-types.md#resourcecolor) | 是   |      背板蒙版颜色。                    |
776
777**示例:**
778
779请参考[animate](#animate11)
780
781  ### animate<sup>11+</sup>
782
783animate(options: AnimationOptions, handler: () => void): void
784
785设置背板蒙版颜色变化动效,在OnDrop和OnDragEnd回调中使用不生效,仅支持通过 [getDragPreview()](js-apis-arkui-UIContext.md#getdragpreview11) 方法获取到的对象上使用。
786
787**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
788
789**系统能力:** SystemCapability.ArkUI.ArkUI.Full
790
791**参数:**
792
793| 参数名   | 类型                             | 必填 | 说明                               |
794| -------- | -------------------------------- | ---- | -----------------------------------|
795| options  | [AnimationOptions](#animationoptions11)                | 是   | 动效参数。                           |
796| handler  | () => void                         | 是   | 用于修改背板蒙版颜色等属性的回调方法。  |
797
798**示例:**
799
800> **说明:**
801>
802> 推荐通过使用[UIContext](js-apis-arkui-UIContext.md#uicontext)中的[getDragController](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取当前UI上下文关联的DragController对象。
803
8041.在EntryAbility.ets中获取UI上下文并保存至LocalStorage中。
805  ```ts
806import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
807import { hilog } from '@kit.PerformanceAnalysisKit';
808import { window, UIContext } from '@kit.ArkUI';
809
810let uiContext: UIContext;
811let localStorage: LocalStorage = new LocalStorage('uiContext');
812
813export default class EntryAbility extends UIAbility {
814  storage: LocalStorage = localStorage;
815
816  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
817    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
818  }
819
820  onDestroy(): void {
821    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
822  }
823
824  onWindowStageCreate(windowStage: window.WindowStage): void {
825    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
826
827    windowStage.loadContent('pages/Index', this.storage, (err, data) => {
828      if (err.code) {
829        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
830        return;
831      }
832      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
833      windowStage.getMainWindow((err, data) => {
834        if (err.code) {
835          hilog.error(0x0000, 'Failed to abtain the main window. Cause:' + err.message, '');
836          return;
837        }
838        let windowClass: window.Window = data;
839        uiContext = windowClass.getUIContext();
840        this.storage.setOrCreate<UIContext>('uiContext', uiContext);
841      })
842    });
843  }
844}
845  ```
8462.在Index.ets中通过this.getUIContext().getSharedLocalStorage()获取UI上下文,进而获取DragController对象实施后续操作。
847  ```ts
848
849import { unifiedDataChannel } from '@kit.ArkData';
850import { hilog } from '@kit.PerformanceAnalysisKit';
851import { dragController, curves, promptAction, UIContext } from "@kit.ArkUI";
852import { image } from '@kit.ImageKit';
853import { BusinessError } from '@kit.BasicServicesKit';
854
855@Entry()
856@Component
857struct DragControllerPage {
858  @State pixmap: image.PixelMap|null = null;
859  storages = this.getUIContext().getSharedLocalStorage();
860
861  @Builder DraggingBuilder() {
862    Column() {
863      Text("DraggingBuilder")
864        .fontColor(Color.White)
865        .fontSize(12)
866    }
867    .width(100)
868    .height(100)
869    .backgroundColor(Color.Blue)
870  }
871
872  @Builder PixmapBuilder() {
873    Column() {
874      Text("PixmapBuilder")
875    }
876    .width(100)
877    .height(100)
878    .backgroundColor(Color.Blue)
879  }
880
881  build() {
882    Column() {
883      Button('拖拽至此处')
884        .margin(10)
885        .onDragEnter(() => {
886        try {
887          let uiContext: UIContext = this.storages?.get<UIContext>('uiContext') as UIContext;
888          let previewObj: dragController.DragPreview = uiContext.getDragController().getDragPreview();
889          let foregroundColor: ResourceColor = Color.Green;
890
891          let previewAnimation: dragController.AnimationOptions = {
892            curve: curves.cubicBezierCurve(0.2,0,0,1),
893          }
894          previewObj.animate(previewAnimation, () => {
895            previewObj.setForegroundColor(foregroundColor);
896          });
897        } catch (error) {
898          let msg = (error as BusinessError).message;
899          let code = (error as BusinessError).code;
900          hilog.error(0x0000, `show error code is ${code}, message is ${msg}`, '');
901        }
902      })
903        .onDrop(() => {
904          this.getUIContext().getPromptAction().showToast({duration: 100, message: 'Drag Success', bottom: 400})
905        })
906      Button('拖起').onTouch((event?:TouchEvent) => {
907        if(event){
908          if (event.type == TouchType.Down) {
909            let text = new unifiedDataChannel.Text()
910            let unifiedData = new unifiedDataChannel.UnifiedData(text)
911            let dragInfo: dragController.DragInfo = {
912              pointerId: 0,
913              data: unifiedData,
914              extraParams: ''
915            }
916            class tmp{
917              event:DragEvent|undefined = undefined
918              extraParams:string = ''
919            }
920            let eve:tmp = new tmp()
921            this.getUIContext().getDragController().executeDrag(() => { // 建议使用 this.getUIContext().getDragController().executeDrag()接口
922              this.DraggingBuilder()
923            }, dragInfo, (err , eve) => {
924              hilog.info(0x0000, `ljx ${JSON.stringify(err)}`, '')
925              if (eve && eve.event) {
926                if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) {
927                  hilog.info(0x0000, 'success', '');
928                } else if (eve.event.getResult() == DragResult.DRAG_FAILED) {
929                  hilog.info(0x0000, 'failed', '');
930                }
931              }
932            })
933          }
934        }
935      }).margin({top:100})
936    }
937    .width('100%')
938    .height('100%')
939  }
940}
941  ```
942  ![zh-cn_executeDrag5](figures/executeDrag5.gif)
943
944## DragStartRequestStatus<sup>18+</sup>
945
946定义应用是否可以发起拖拽的枚举类型。
947
948**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
949
950**系统能力:** SystemCapability.ArkUI.ArkUI.Full
951
952| 名称     | 值 | 说明                                                         |
953| -------- | -- | ------------------------------------------------------------ |
954| WAITING   | 0 | 应用准备数据中,无法发起拖拽。 |
955| READY | 1 | 应用数据准备完成,可以发起拖拽。 |