Flex菜单控制 - 单击按钮,将显示一个菜单。如何再次单击该按钮并隐藏该菜单?

时间:2010-06-20 02:14:09

标签: flex menu controls

基本上,我有一个按钮,点击它会显示一个菜单。我想再次点击该菜单,菜单关闭。目前,每次单击该按钮,菜单都会重新打开。我粘贴了下面的Flex liveoc示例。如果单击该按钮,菜单将继续重新打开。

现在,我通过将var设置为打开和关闭来装配它,因此当单击按钮时它会进行检查。但是,如果您单击屏幕,则会调度HIDE事件,并关闭菜单。这搞砸了开放的close var。

我怎样才能使下面的Flex示例显示按钮单击上的菜单,然后在第二个按钮单击时,它会关闭菜单?如果你点击菜单,就会关闭它。

另外,我使用了按钮的MOUSE_DOWN_OUTSIDE事件并设置了preventDefault,并且FlexMouseEvent event.cancelable设置为false。

不能选择更改为PopUpMenuButton。我需要进行大量的剥皮。

以下是Flex示例:

<mx:Script>
    <![CDATA[
        // Import the Menu control.
        import mx.controls.Menu;

        // Create and display the Menu control.
        private function createAndShow():void {
            var myMenu:Menu = Menu.createMenu(null, myMenuData, false);
            myMenu.labelField="@label";
            myMenu.show(10, 10);
        }
    ]]>
</mx:Script>

<!-- Define the menu data. -->
<mx:XML format="e4x" id="myMenuData">
    <root>
        <menuitem label="MenuItem A" >
            <menuitem label="SubMenuItem A-1" enabled="false"/>
            <menuitem label="SubMenuItem A-2"/>
        </menuitem>
        <menuitem label="MenuItem B" type="check" toggled="true"/>
        <menuitem label="MenuItem C" type="check" toggled="false"/>
        <menuitem type="separator"/>     
        <menuitem label="MenuItem D" >
            <menuitem label="SubMenuItem D-1" type="radio" 
                groupName="one"/>
            <menuitem label="SubMenuItem D-2" type="radio" 
                groupName="one" toggled="true"/>
            <menuitem label="SubMenuItem D-3" type="radio" 
                groupName="one"/>
        </menuitem>
    </root>
</mx:XML>

<mx:VBox>
    <!-- Define a Button control to open the menu -->
    <mx:Button id="myButton" 
        label="Open Menu" 
        click="createAndShow();"/>
</mx:VBox>

1 个答案:

答案 0 :(得分:2)

//Declare menu as an instance variable instead of a local var
private var myMenu:Menu;

//var to store menu status
private var isMenuVisible:Boolean

//Create the Menu control. call this from the creationComplete of the 
//application or the Component that it is part of.
private function createMenu():void 
{
    var myMenu:Menu = Menu.createMenu(null, myMenuData, false);
    myMenu.labelField="@label";
    //menu fires an event when it is hidden; listen to it.
    myMenu.addEventListener(MenuEvent.MENU_HIDE, onMenuHidden);
}
private function onMenuHidden(e:MenuEvent):void
{
    /*
    menuHide event fired whenever the menu or one of its submenus
    are hidden - makes sure it was indeed the main menu that was hidden
    I don't have compiler handy to test this, so if for 
    some reason comparing myMenu with e.menu doesn't work,
    try if(e.target == myMenu) instead; 
    And please let me know which one works via comment :)
    */

    if(e.menu == myMenu)
       isMenuVisible = false;
}
//call this from button's click 
private function toggleMenu():void
{
    if(isMenuVisible)
        myMenu.hide();
    else
        myMenu.show();
}