Lately i was working on a drag and drop for my project and i have to allow the user to drag and item from one container to another container. Somehow the drag and drop was not working though the code looks fine.The drag manager was not allowing to drop the item on the target container. This was freaking me out as the drag and drop handling code seems ok. After searching on the internet i found that to use container as a drop target, the background color of the container should not be transparrent as doing so the drag and drop manager will not be able to detect whether the mouse pointer is on a possible drop target.The backgroundColor property should be set for this to work.
The code shown below uses simple drag and drop of an image within a container:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%" layout="horizontal" borderColor="#3D7FAD" horizontalAlign="center" verticalAlign="middle"> <mx:Script> <![CDATA[ import mx.containers.Canvas; import mx.events.DragEvent; import mx.controls.Image; import mx.core.IUIComponent; import mx.managers.DragManager; import mx.core.DragSource; private function mouseMoveHandler( evt:MouseEvent ):void { var dragInitiator:Image=Image(evt.currentTarget); var ds:DragSource = new DragSource(); ds.addData(dragInitiator, "test"); DragManager.doDrag(dragInitiator, ds, evt); } private function dragEnterHandler( evt:DragEvent ):void { if (evt.dragSource.hasFormat("test")) { DragManager.acceptDragDrop(Canvas(evt.currentTarget)); } } private function dropHandler( evt:DragEvent ):void { evt.dragSource.dataForFormat("test").x = evt.currentTarget.mouseX; evt.dragSource.dataForFormat("test").y = evt.currentTarget.mouseY; } ]]> </mx:Script> <mx:Canvas width="90%" height="90%" dragEnter="dragEnterHandler(event);" dragDrop="dropHandler(event);" borderColor="#2D5A7A" borderStyle="solid"> <mx:Image id="img" width="40" height="40" source="@Embed('../assets/task.png')" mouseMove="{mouseMoveHandler(event)}" /> </mx:Canvas> </mx:Application>
the demo is shown below:
As you can see the drag and drop is not working due to the background of the container being transparrent. Now if we set the backgroundColor property of the container as backgroundColor="#EEEEEE", the drag and drop will work which is shown below.
Sometimes, these minor problems can take considerable time to get to the solution. I will be careful from now on ... :).
... comment