Creating a Custom Generic Flex Context Menu Component

27. July 2009 09:25

When you right-click in a flash/flex application, the built-in context menu appears allowing you to perform both custom and built-in actions.  There are a few menu items that will always remain, however, most can be removed.  The following image shows how your menu will appear once you have called the ContextMenu.hideBuiltInItems() method on your new component.



What we want here is just a simple reusable component that will redirect the user to a company url when the menu item is clicked.  So we create a new class:

package
{
    import flash.events.ContextMenuEvent;
    import flash.net.URLRequest;
    import flash.ui.ContextMenu;
    import flash.ui.ContextMenuItem;
    import flash.net.navigateToURL;
   
    import mx.core.Application;
   
    public class MyCustomContextMenu   
{
        private var comp:String = 'FlexAdmiral';
        private var link:String = 'http://flexadmiral.com';
        private var cm:ContextMenu;
       
        public function ContextMenu_Silkroad(companyName:String='', companyUrl:String='')
        {
            if(companyName != '')
            {
                this.comp = companyName;
            }
            if(companyUrl != '')
            {
                if(companyUrl.toLowerCase().substring(0, 7) != 'http://')
                {
                    this.link = 'http://';
                    this.link += companyUrl;
                }
                else
                {
                    this.link = companyUrl;
                }
               
            }
            cm = new ContextMenu();
            cm.hideBuiltInItems();
            var companyItem:ContextMenuItem = new ContextMenuItem(comp);
            companyItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, handleContextItemClick);               
            cm.customItems.push(companyItem);
            Application.application.contextMenu = cm;           
        }
        private function handleContextItemClick(event:ContextMenuEvent):void
        {
            navigateToURL(new URLRequest(link));   
        }

    }
}

that's it.  easy-peasy.  In the constructor, we check to see if the user has supplied a name and redirect url.  If not, we use the default for Flexadmiral.com.  Setting the application context menu here (ie Application.application.contextMenu = cm) means that all we need to do in the application is to instantiate the class and our MyCustomContextMenu class will take care of the rest.

Cheers 

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Log in