Archive for the ‘Flex/Flash/Actionscript’ Category

Drag ‘n Drop reorder in an HBox

Friday, June 26th, 2009

It’s a bit off topic, but I was googling for an example of reordering images in an HBox using drag and drop. I came up empty, but I also found that there were a few other people asking for help doing the same thing, so I figured I’d post my solution here.

Assuming you’ve set up your image list (I’ve included an xml list of images in the source) the idea is pretty simple. Loop through the images, and add them to an array. With each image add the appropriate listeners so that they know how to handle being dragged, dragged over, and dropped on. The array is used to keep track of the image positions in the HBox, and gets reshuffled each time an image changes it’s position.

First things first, grab your list of image data. I’m calling a php page and grabbing the list from the database. My php assembles the xml for me, but I’ve included some sample xml in the source. Once you grab that you process the images, pushing each image to the array and making sure to add your listeners.

for(var i:int=0; i<ListData.image.length(); i++){         var ImageObject:Object = new Object();         var nextInLine:XML = ListData.image[i];                 ImageObject.source_path = nextInLine.elements("name");         ImageObject.image_id = nextInLine.elements("image_id");                 var nextImage:Image = new Image();                 nextImage.addEventListener(MouseEvent.MOUSE_DOWN, initDragImageProc);                 nextImage.addEventListener(DragEvent.DRAG_DROP,dragImageDropHandler);                 nextImage.addEventListener(DragEvent.DRAG_ENTER,dragImageEnterHandler);                 nextImage.buttonMode = true;                 nextImage.source = ImageObject.source_path;                 nextImage.id = ImageObject.image_id;                 nextImage.width = 100;                 nextImage.height = 100;                 ImageArray.push(nextImage);         h_image_list.addChild(nextImage);         }

The interesting stuff happens when you perform the drag.

/**  * reorder the images  **/ private function dragImageDropHandler(event:DragEvent):void {                 // this is the image you are dragging                 var theImage:Image = event.dragInitiator as Image;         // this is the image you dropped the dragged image onto                 var theTarget:Image = event.target as Image;         // find the index of the target image in the image array                 var toImageIndex:int = ImageArray.indexOf(theTarget);         // set the index of the dragged child equal to the index of the target image                    this.h_image_list.setChildIndex(theImage,toImageIndex);         //refresh the array so that the indices represent the new order in the HBox                 reorderImageArray(); }

Take a look at it here. View source to enjoy a download =)