Quality Reads

Thursday, July 26, 2007

Drag & Drop in AIR

I just ran into a great article by Alastair outlining the use of Native Drag & Drop functionality in AIR (w/ a little RoR mixin). The documentation for Native D&D is very spotty, there are more mistakes then anything else. So, if you haven't learned the hard way yet, let me make your life a little easier: http://blog.vixiom.com/2007/06/29/merb-on-air-drag-and-drop-multiple-file-upload/

Here's a simple test application you can use to get started:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init(event)">

<mx:Script>
<![CDATA[
import mx.events.DragEvent;
import flash.desktop.DragManager;
import flash.desktop.DragActions;
import flash.events.NativeDragEvent;
import flash.desktop.TransferableFormats;
import flash.filesystem.File;

private function init(e:Event):void
{
//add the event handlers
this.addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER, onEnter);
dropPanel.addEventListener(NativeDragEvent.NATIVE_DRAG_DROP, onDrop);
}

public function onEnter(event:NativeDragEvent):void
{
//Check to see if the drag item is the right format
if(event.transferable.hasFormat(TransferableFormats.FILE_LIST_FORMAT))
{
DragManager.acceptDragDrop(dropPanel);
}
}

public function onDrop(event:NativeDragEvent):void{
trace("dropped");
// Cast the drag & drop data as an array
var files:Array = event.clipboard.dataForFormat(flash.desktop.ClipboardFormats.FILE_LIST_FORMAT) as Array;
for each (var f:File in files)
{
// check out the file URL
trace(f.url);
}
}
]]>
</mx:Script>

<mx:Panel id="dropPanel"
top="10"
left="10"
height="100"
width="100"
title="Drop Files Here"
backgroundColor="#FFF">


</mx:Panel>

</mx:WindowedApplication>



Also worth a read: http://coenraets.org/blog/2007/06/air-to-desktop-drag-and-drop-two-simple-utility-classes/

I'll let you know why I'm reading up on D&D in a couple days :)

Cheers,
Todd

***Updated for AIR Beta 2***

3 comments:

Anonymous said...

For flex3 beta 2 I had to change a few lines:

var files:Array = event.transferable.dataForFormat( TransferableFormats.FILE_LIST_FORMAT ) as Array;

to:

var dropfiles:Array = event.clipboard.dataForFormat(flash.desktop.ClipboardFormats.FILE_LIST_FORMAT) as Array;

and the import to:

import flash.desktop.ClipboardFormats;

Todd Cullen said...

Thanks letting me know. I probably wouldn't have updated this post otherwise.

-Todd

Anonymous said...

var dropfiles:Array = event.clipboard.dataForFormat(flash.desktop.ClipboardFormats.FILE_LIST_FORMAT) as Array; also does not work. It gets rid of one error however it still leaves the error
1061: "Call to a possibly undefined method dataForFormat through a reference with static type flash.desktop:Clipboard."