如何获取Menu当前选择项的路径

如何获取menu当前选择项的路径?通常情况下,我们需要遍历当前选择节点的父节点。下面是完整代码。

<?xml version="1.0"?> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 
    <mx:Script> 
        <![CDATA[ 
            import mx.controls.Menu; 
  
            import mx.events.MenuEvent; 
              
            [Bindable] 
            private var paths:Array; 
              
            private var menubarXML:XML = 
                <menuitems> 
                    <menuitem label="File"> 
                        <menuitem label="New" data="1-1"/> 
                        <menuitem label="Open" data="1-2"/> 
                    </menuitem> 
                    <menuitem label="Search"> 
                    <menuitem label="Search..." data="2-1"/> 
                    <menuitem label="File..." data="2-2"/> 
                    <menuitem label="Declaration"> 
                            <menuitem label="File" data="2-3-1"/> 
                            <menuitem label="Project" data="2-3-2"/> 
                            <menuitem label="WorkSpace" data="2-3-3"/> 
            </menuitem> 
            <menuitem label="References"> 
                            <menuitem label="File" data="2-4-1"/> 
                            <menuitem label="Project" data="2-4-2"/> 
                            <menuitem label="WorkSpace" data="2-4-3"/> 
                            </menuitem> 
                    </menuitem> 
                    <menuitem type="separator"/> 
                    <menuitem label="About" data="3"/> 
                </menuitems>; 
  
            private function addMenu():void { 
                paths = new Array(); 
                var menu:Menu = Menu.createMenu(null, menubarXML, false); 
                menu.labelField="@label"; 
                    var pt:Point = new Point(25, 65); 
                    pt = panel.localToGlobal(pt); 
                  
                    menu.show(pt.x, pt.y); 
                    menu.addEventListener(MenuEvent.ITEM_CLICK, itemClickHandler); 
  
            }         
            private function itemClickHandler(event:MenuEvent):void{ 
                findParent(event.item); 
                function findParent(xml:XML):void{ 
                    if(xml.parent()!=null){ 
                        findParent(xml.parent()); 
                        paths.push(xml.@label); 
                    } 
                } 
                lblPath.text = paths.toString(); 
            } 
         ]]> 
    </mx:Script> 
      
    <mx:Panel id="panel" title="Menu"
         paddingTop="10" paddingLeft="10" height="100%" width="100%"> 
        <mx:Button id="btn" label="Show Menu" click="this.addMenu()" /> 
        <mx:ApplicationControlBar> 
            <mx:Label id="lblPath"/> 
        </mx:ApplicationControlBar> 
    </mx:Panel> 
</mx:Application>

核心代码位于itemClickHandler事件侦听函数中,我们这里使用了递归算法。

点击此处查看最终效果。

发表评论