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