Add drag and drop support manually

June 10th, 2009 in Flex

This tutorial teaches how to manually add drag-and-drop interactions to your Flex application.
We illustrate this by creating an application that let the user dragging and dropping gift into a cart.

View DemoDownload Source

If Flex includes built-in support for the drag-and-drop operation for certain controls (see our post on How to add drag and drop support to datagrids) you can manually add support for drag and drop to all other Flex components.

1. Create a new Flex project. Set the application layout to vertical.

2. Add a Canvas component. Inside the Canvas, we add two Image components. One for the cart which is the drop target and one for the gift which is the dragging object.

<mx:Canvas width="800" height="366">
<mx:Image source="assets/gift.png" x="40" y="120"/>
<mx:Image source="@Embed('assets/cart.jpg')"
x="480" y="100"/>
</mx:Canvas>

3. Beneath the cart, add a Label to display the cart’s quantity.

<mx:Label fontSize="14" color="#000000" width="66" x="600" y="311"
fontWeight="bold" textAlign="center"/>

4. Create a Script tag and declare a bindable variable that holds the quantity of gifts that the user has added to the cart.

<mx:Script>
<![CDATA[

[Bindable]
private var quantity : int = 0;

]]>
</mx:Script>

Now we can bind the text property of the Label with this variable.

<mx:Label fontSize="14"
color="#000000" width="66" x="600" y="311"
fontWeight="bold" textAlign="center"
text="{quantity.toString()}"/>

5. Next we add the drag and drop event listeners to our components.
In order to drag the gift we add a mouseDown event.
In order to have a functional drop cart, we add a dragEnter and a dragDrop events.

<mx:Image source="assets/gift.png" x="40" y="120"
mouseDown="initiateDrag(event)" />
<mx:Image source="@Embed('assets/cart.jpg')" x="480" y="100"
dragEnter="dragEnterHandler(event)"
dragDrop="dragDropHandler(event)" />

6. Next we write the functions that handles all these events :

6.i . The initiateDrag function handles the mouseDown event on the gift and initiates the drag and drop operation.
We instantiate a drag source object to hold the data being dragged.
We specify a drag proxy, which is optional, which is displayed while the object being dragged.

private function initiateDrag(event:MouseEvent):void {

     var dragInitiator:Image = event.currentTarget as Image;

     var source:DragSource = new DragSource();
     source.addData(dragInitiator,"gift");

     var proxy:Image = new Image();
     proxy.source = dragInitiator.source;
     proxy.width = 50;
     proxy.height = 50;

     DragManager.doDrag(dragInitiator, source, event, proxy);
}

6.ii . The dragEnterHandler function determines whether the data being dragged is in a format that the target accepts. If so, to accept the drop, we call the DragManager.acceptDragDrop() method.

private function dragEnterHandler(event:DragEvent):void {
      if (event.dragSource.hasFormat("gift")){
      DragManager.acceptDragDrop(event.currentTarget as Image);
      }
}

6.iii . Finally we implement the dragDropHandler function that handles the dragDrop event that is dispatched by the component that has accepted the dragged item.
The function increments the quantity number and displays a message.

private function dragDropHandler(event:DragEvent):void{
      quantity ++;
      Alert.show("Gift added to your cart");
}

7. The final code is beneath :

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
	 backgroundGradientAlphas="[1.0, 1.0]"
	 backgroundGradientColors="[#FFFFFF, #FFFFFF]">

  <mx:Script>
    <![CDATA[
      import mx.controls.Alert;
      import mx.core.DragSource;
      import mx.managers.DragManager;
      import mx.events.DragEvent;

      [Bindable]
      private var quantity : int = 0;

      private function initiateDrag(event:MouseEvent):void {

          var dragInitiator:Image = event.currentTarget as Image;

	       var source:DragSource = new DragSource();
	       source.addData(dragInitiator,"gift");

	       var proxy:Image = new Image();
	       proxy.source = dragInitiator.source;
	       proxy.width = 50;
	       proxy.height = 50;

	       DragManager.doDrag(dragInitiator, source, event, proxy);
      }

      private function dragEnterHandler(event:DragEvent):void {
	        if (event.dragSource.hasFormat("gift")){
	          DragManager.acceptDragDrop(event.currentTarget as Image);
	        }
	  }

      private function dragDropHandler(event:DragEvent):void{
	      	quantity ++;
	        Alert.show("Gift added to your cart");
      }

    ]]>
  </mx:Script>

  <mx:Label text="Add drag and drop support manually" color="#990000"
  	 fontSize="20" fontWeight="bold" fontStyle="italic"/>

  <mx:Canvas width="800" height="366">
		<mx:Label fontSize="14"
			 color="#000000" width="66" x="600" y="311"
			 fontWeight="bold" textAlign="center"
			 text="{quantity.toString()}"/>
	    <mx:Image source="assets/gift.png" x="40" y="120"
	    	 mouseDown="initiateDrag(event)" />
	    <mx:Image source="@Embed('assets/cart.jpg')" x="480" y="100"
	      dragEnter="dragEnterHandler(event)"
	      dragDrop="dragDropHandler(event)" />
  </mx:Canvas>

</mx:Application>

8. Run the application to test it.

  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Twitter


What you think ...

(2 Comments)

+ Add a Comment
  1. samBrown
    Jun 10th, 2009

    cool tut – thanks. Going to play around with this later..

  2. GuruShare
    Jun 19th, 2009

    This is a really great tutorial and thank you for creating it. If you feel like creating a video of this tutorial we have a $1000 USD contest running for the best video tutorial. We are a social learning network and we would love to have great work like this displayed for everyone to learn from. Check us out @ http://www.gurushare.com, but regardless, thank you again for a solid tutorial.

Leave a Comment

Name (required)

E-mail (required, will not be published)

Website