Flex【原创】拖入文件到List (仅限Air)

这里抛砖引玉,封装一个支持拖入文件的List

1:DragList类:

package
{
    import flash.desktop.Clipboard;
    import flash.desktop.ClipboardFormats;
    import flash.desktop.NativeDragActions;
    import flash.desktop.NativeDragManager;
    import flash.display.InteractiveObject;
    import flash.events.NativeDragEvent;
    import flash.filesystem.File;
    
    import mx.collections.ArrayCollection;
    
    import spark.components.List;
    
    /**
     * the List supported drag files into it
     * 
     * @author binyy
     * @date 2012-07-17
     * */
    public class DragList extends List
    {
        [bindable]public var photoArray:ArrayCollection = null;
        
        public function DragList()
        {
            super();
            addDragListListeners();
        }
        
        //add listener for drag
        protected function addDragListListeners():void
        {
            this.addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER,onDragIn);
            this.addEventListener(NativeDragEvent.NATIVE_DRAG_DROP,onDragDrop);
        }
        
        //when draging files from Desktop
        protected function onDragIn(e:NativeDragEvent):void
        {
            var filesInClip:Clipboard = e.clipboard;
            if(filesInClip.hasFormat(ClipboardFormats.FILE_LIST_FORMAT))
            {
                NativeDragManager.acceptDragDrop(e.target as InteractiveObject);
                NativeDragManager.dropAction = NativeDragActions.MOVE;
            }
        }
        
        //when drop files into the List
        protected function onDragDrop(e:NativeDragEvent):void
        {
            var filesArray:Array = e.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
            
            photoArray = new ArrayCollection();
            
            for(var i:Object in filesArray)
            {
                var file:File = filesArray[i];
                if(file.extension == "png" || file.extension == "jpg" || file.extension == "gif" || file.extension == "jpeg")
                {
                    photoArray.addItem(file);
                }
            }
            
            this.dataProvider = photoArray;
            
        }
        
    }
}

2:调用方式

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
                       xmlns:s="library://ns.adobe.com/flex/spark" 
                       xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:local="*">
    <local:DragList width="100%" height="100%" labelField="name"/>
</s:WindowedApplication>

3:示例截图

此例针对于拖入图片文件,大家可以根据自己的需求进行封装与拓展~

原文地址:https://www.cnblogs.com/loveFlex/p/2595174.html