Archive

Posts Tagged ‘NativeMenuItem’

Custom Context Menu with Air

April 14, 2011 Leave a comment

What if you want to create a custom context menu for say a “Canvas” or a “TextInput” ?

To develop a custom context menu for a component we first need to understand the mx.internal property of a UI component. Here I am taking a TextInput for an example.

Let’s say you have a requirement to edit the font style in TextInput when you right click on a TextInput’s text area. By default context menu will come with a predefined set of options like Cut, Copy, Paste etc.  But here we need to add one more custom feature “Fonts” in the context menu.

To get this done, we need to reach to the “TextField” of a TextInput. We can get this object by using mx.internal property of a TextInput.


var txt:TextField = messageView.txtChatMessage.mx_internal::getTextField() as TextField;

mx.internal is basically those properties of an objext which has a scope of change in future. So these properties are kept hidden and not available to us. To get access these peroperties just add following piece of line at the beging of your class at import level.


use namespace mx_internal;

Now we have a full access to the TextField object of a TextArea. Following method  createCustomContextMenu() has been called on the right click of a TextArea component.

private function createCustomContextMenu () : void
{
     var txt:TextField = messageView.txtChatMessage.mx_internal::getTextField() as TextField;
}

Now create an object of NativeMenuItem, which will represents our customMenuItem. You need to add an event listener also for the same. You would also like to give a “name” to you Context Menu item together with some “data”  using the “name” and “data” property respectively.Finally you need to add this item in your components contextmenu object. Following is an updated version of the createCustomContextMenu() method.

private function createCustomContextMenu() : void
{

     var txt:TextField = messageView.txtChatMessage.mx_internal::getTextField() as TextField;

     var suggestedWord:NativeMenuItem = new NativeMenuItem(suggestionArray[iCount].toString());

     suggestedWord.addEventListener(Event.SELECT,onWordItemSelect);

     suggestedWord.data = "You menu item Label<strong>"</strong>;

     suggestedWord.name = suggestionArray[iCount].toString();

     txt.contextMenu.addItemAt(suggestedWord,0);

}

In this example I am adding my custom Menu Item at 0th location i.e. the first position. This location can be changed using “”addItemAt()” method of you context menu object.

There are other useful properties available like checked, enabled, mnemonicIndex etc. to be used if required.

You can get a better idea of all these option from livedoc’s following link.

http://livedocs.adobe.com/flex/3/html/help.html?content=Menus_2.html