通过加载外部xml文件的数据,自定义右键菜单。
xml文件(setup.xml)
文档类menuItem.as
xml文件(setup.xml)
<?xml version="1.0" encoding="UTF-8"?>
<shell>
<menu>
<item url="http://www.baidu.com">访问 百度</item>
<item url="http://www.google.com.hk">访问 谷歌</item>
</menu>
</shell>
文档类menuItem.as
package {
import flash.display.Sprite;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
import flash.xml.*;
import flash.net.navigateToURL
import flash.events.ContextMenuEvent;
import flash.ui.*;
/**
* ...
* 文档类
* @author zkl
* 2010-9-13 16:45
*/
public class menuItem extends Sprite {
private var _xml:XML;
private var _urlLoad:URLLoader;
private var _url:URLRequest;
private var _myMenu:ContextMenu = new ContextMenu;
private var _menu:String;
private var _menus:Array;
public function menuItem():void {
init();
}
private function init():void {
//加载xml文件
_xml = new XML;
_xml.ignoreWhite = true;
_url = new URLRequest("setup.xml");
_urlLoad = new URLLoader(_url);
//加载完成
_urlLoad.addEventListener(Event.COMPLETE, loadComplete)
}
private function loadComplete(e:Event):void {
_urlLoad.removeEventListener(Event.COMPLETE, loadComplete)
_xml = XML(_urlLoad.data)
//隐藏默认菜单
_myMenu.hideBuiltInItems();
//分析xml文件,将菜单放置在_menus数组
_menus = new Array;
for (var s:String in _xml.menu.item){
var obj:Object = new Object;
obj.name = _xml.menu.item[s];
obj.url = _xml.menu.item[s].@url;
_menus.push(obj);
//添加自定义的右键菜单
var customMenu:ContextMenuItem = new ContextMenuItem(obj.name)
customMenu.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, menuHandler);
_myMenu.customItems.push(customMenu);
}
contextMenu = _myMenu;
//释放内存
_xml = null;
_urlLoad = null;
}
private function menuHandler(e:ContextMenuEvent):void {
navigateToURL(new URLRequest(_menus[_myMenu.customItems.indexOf(e.target)].url), "_blank");
}
}
}