Placing a ContextMenu on TextArea in AIR 1.5

The TextArea in Flex comes with its own contextual menu, so adding one does absolutely nothing but leave you wondering what the heck you are doing wrong. In the bug report there is a bit of a work around for AIR 1.5 which requires you to access the “textField” property of the TextArea and add your contextMenu to that item. Apparently there are not enough people using custom contextMenu’s to justify fixing the bug. The problem gets a bit trickier as the textField is protected in Flex Builder 3, so you can’t just do:

myTextArea.textfield.contextMenu = myMenu;

You need to expose or get at the textField to add the menu. You can do this by using mx_internal (careful, kid, or you’ll put your eye out with that thing!). So you can throw a little hack together to get your context menu on your text area:

private function createMenu():void
     var mainMenu:ContextMenu = new ContextMenu();

     var menuitem:ContextMenuItem = new ContextMenuItem("hello mom!");
     menuitem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, handleContextMenuEvent);

     textInput.contextMenu = mainMenu;

     var txt:TextField = textInput.mx_internal::getTextField() as TextField;
     txt.contextMenu = mainMenu;

private function handleContextMenuEvent(event:ContextMenuEvent):void
    var menuitem:ContextMenuItem = as ContextMenuItem;
    trace("context menu event: " + menuitem);

<mx:TextArea id="textInput"  width="100%" height="100%">

Notice that I added the contextMenu to two spots, the textField inside the TextArea, and the TextArea itself, this will show only the “hello mom!”. If you wanted to just add “hello mom!” to the existing menu options of the TextArea (copy/paste/select all), then you can just add the menu to the textField only.

I thought I might be able to accomplish the same behavior using an AIR NativeMenu/NativeMenuItem. Using a NativeMenu instead of a ContextMenu item on a TextArea throws this error:

ReferenceError: Error #1069: Property clipboardItems not found on flash.display.NativeMenu and there is no default value.
at flash.display::InteractiveObject/onContextMenuEvent()

The workaround would then be to create a NativeMenu popup and position on the cursor position of the TextArea.

private function createMenu():void
     var mainMenu:NativeMenu = new NativeMenu();

     var menuitem:NativeMenuItem = new NativeMenuItem("hello mom!");
     menuitem.addEventListener(Event.DISPLAYING, handleDisplaying);

     mainMenu.display(NativeApplication.nativeApplication.activeWindow.stage, 20, 20);

private function handleDisplaying(event:Event):void
    trace("native menu displayed");


One Comment

Comments are closed.