Positioning icon on MenubarItem

Well, generally when you use the feature provided by flex (iconField option - check Display icons in ComboBox / Menu / Menubar for more information on this) to add icon to the menubar items, the icon will be added to the left of the label. But say for example, you want the menubaritem to behave the same way as tabs in browser where the delete ("X") icon is displayed towards the right of the label, how will you make it happen? HHmmmm... IconField option wont help you. You need to customize the menubar itemrenderer and use the same. Lets see how? Very simple. I will say, just 2 steps as usual :-)


Positioning icons on MenubarItem

Lets jump directly into steps and see.

Step 1: As a first step, you need to create your custom menubaritemrenderer that extends MenuBarItem class and override updateDisplayList function of the MenuBarItem class. In this function, you will add icons as children to MenuBarItem and position them as below.



public class CustomMenuBarItemRenderer extends MenuBarItem{
	
  [Embed("/assets/delete.png")]
  public var cancel:Class;

  private var cancelIcon:DisplayObject;

  override protected function updateDisplayList(unscaledWidth:Number,
                                           unscaledHeight:Number):void {
    super.updateDisplayList(unscaledWidth, unscaledHeight);

    if(this.cancelIcon!= null) removeChild(this.cancelIcon);

    cancelIcon = addChild(new cancel());

    this.label.x -= 6;

    cancelIcon.visible = true;
    cancelIcon.x = unscaledWidth-14;
    cancelIcon.y = (unscaledHeight-10)/2;
  }
}


Well, whats going on here. As simple as it is, in updateDisplayList(...) function, the icon which is nothing but image is added as child to MenuBarItem. This child is nothing but "DisplayObject". Now you have the DisplayObject and you need to place it where you want it to be. If you look at the code of the MenuBarItem, the label will have padding and since I wanted to adjust the icon in the menubaritem to fit perfectly on the right site, I moved label 6 pixels left (this.label.x -= 6) and then positioned it to right. You can see that from "unscaledWidth-14" which is nothing but the width of menubaritem minus 14 pixels and in the center vertically by "(unscaledHeight-10)/2". Thats all, now your icon is positioned towards right.

Step 2: The next step is using this custom menubar itemrenderer. You need to simply set the full path of the Custom menubar itemrenderer to "menuBarItemRenderer" property of "MenuBar" and you are done.



<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    backgroundColor="#FFFFFF" 
    initialize="init()">

    ... 

  <mx:MenuBar id="myMenuBar" menuBarItemRenderer="CustomMenuBarItemRenderer" labelField="label"/>
</mx:Application>	



You can download the example source code here.

Download the example code.





blog comments powered by Disqus