Positioning icons in Menu for each MenuItem

As you know well that you can add icons in addition to labels for the Popup Menu items using iconField (check Display icons in ComboBox / Menu / Menubar for more information on this) but these icons by default will be added to the left of the label. So, when you open the menu, you will see icon and next the menu item. Check below.

Sometimes you may have to show the icon to the right of the label like below and ofcourse its based on the requirement but how will you set the icon to the right of the menu item?

Ofcourse there is a very simple solution. Lets see how to do this in two steps as usual.

Step 1: First step - to position icon to the right of the label, you need to create your custom itemrenderer that extends MenuItemRenderer class and override updateDisplayList function of the MenuItemRenderer class. MenuItemRenderer is the itemRenderer generally using by Menu if you dont mention any custom item renderer. It contains icon field which is what you set to display icons in the Menu. But to position the icon to the right of the label, you need to set then "x" and "y" co-ordinates of the icon with respect to the width of the menu item. So generally set the x co-oridinate to (width of the item - width of icon) and y co-ordinate to (height of item/2) or whatever you would like to calculate and set. Done.

package com.jusfortechies.controls
   import mx.controls.menuClasses.MenuItemRenderer;
   public class CustomMenuItemRenderer extends MenuItemRenderer
      override protected function updateDisplayList(unscaledWidth:Number,
                                             unscaledHeight:Number):void {
         super.updateDisplayList(unscaledWidth, unscaledHeight);
         //Adjust label position slightly to left to fit icon on right
         this.label.x -= 10;
         //Check and position icon to right by setting x and y co-ordinates
            this.icon.x = unscaledWidth-24;
            this.icon.y = (unscaledHeight-16)/2;

Step 2: Second step is just using the custom itemrenderer created above by setting it as itemRenderer to Menu. Now you can see the icon is positioned towards right.

<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 

         private var myMenuData:ArrayCollection = new ArrayCollection();

         // Create and display the Menu control.
         private function createAndShow():void {
            var myMenu:Menu = Menu.createMenu(null, myMenuData, false);
            //Set custom itemRenderer
            myMenu.itemRenderer = new ClassFactory(CustomMenuItemRenderer);
         public var Information:Class;
         public function init():void {
            myMenuData.addItem(new ValueObject("MA", "MenuItem A", "Information"));

      <mx:Button id="myButton" initialize="init()" label="Open Menu" click="createAndShow();"/>

You can download the example source code here.

Download the example code.

blog comments powered by Disqus