A Custom Drag-n-Drop List Control for Flex
Recently I have work on a custom component that extend the List class and add more functionalities to that class.The class do a lot of stuff but I decided to write a simple example for the blog that show just one functionality. The problem that this example solve is very simple:
“Make a list control that allow to drag only some of the list items”
The final result looks like this:
The steps to this are:
1) Create a list control and enable drag and drop
<mx:List
id=”plList”
width=”300″
height=”300″
dragEnabled=”true”
dragMoveEnabled=”true”
dropEnabled=”true”
dragOver=”listDragOverHandler(event)” />
2) Create a XML that we will use as a dataProvider
<mx:XML id=”playlists”>
<root>
<pl name=”Playlist1″ icon=”myIcon” canMove=”1″ />
<pl name=”Radio” icon=”myIcon2″ canMove=”0″ />
<pl name=”Random” icon=”myIcon” canMove=”1″ />
<pl name=”Best 90″ icon=”myIcon” canMove=”1″ />
<pl name=”Custom” icon=”myIcon2″ canMove=”0″ />
</root>
</mx:XML>
if you look at the XML you will see that a playlist contains 3 attributes. The name, icon and canMove. The canMove is the important attribute for us because this attribut will tell us if a item can move or not. Now that we have the XML let’s tell our list that we want to use this XML as a dataProvider and the name attribute as label:
<mx:List
id=”usersList”
width=”300″
height=”300″
dragEnabled=”true”
labelField=”@name”
iconField=”@icon”
dataProvider=”{playlists.pl}”
dragMoveEnabled=”true”
dropEnabled=”true”
dragOver=”listDragOverHandler(event)” />
3) Create a function that will be called when a list item is drag
private function listDragOverHandler( event:DragEvent ):void
{
// with this call we are telling that we will
// handle the drag
event.preventDefault();// check to see if selected item can move
var selectedItem :XML = XML(plList.selectedItem);
var move :Number = Number(selectedItem.attribute(’canMove’));// if drag item can move
if (event.dragSource.hasFormat(”items”) && move)
{
// Drag allowed
event.currentTarget.showDropFeedback(event);
DragManager.showFeedback(DragManager.MOVE);return;
}// Drag not allowed.
event.currentTarget.hideDropFeedback(event);
DragManager.showFeedback(DragManager.NONE);
}
And this is all. If you have any questions post them here.
View the example | View Source
Tags: Custom Drag, Example, Flex, List