Sunday, April 10, 2011

Working with menus in AIR: Part 3

In today's tutorial we're going to learn how to listen for the menu item selection events.

For now we have a menu with submenu items that does nothing. We can find out when the user has clicked a menu item if we add a listener for it.

Right now we have this set of items for the submenu:

var subitem1:NativeMenuItem = new NativeMenuItem("Red");
var subitem2:NativeMenuItem = new NativeMenuItem("Blue");
var subitem3:NativeMenuItem = new NativeMenuItem("Green");

We're going to add listeners for each of the items and tell them to call one function called selectItem:

subitem1.addEventListener(Event.SELECT, selectItem);
subitem2.addEventListener(Event.SELECT, selectItem);
subitem3.addEventListener(Event.SELECT, selectItem);

Using target property, we can find out what does the item the user has clicked say:

function selectItem(evt:Event):void
{
trace("You've pressed the " + evt.target.label + " menu item.");
}

But wait, there's more. We can also set a value to the data property of a menu item. We an store whatever we want in it - an object, a string, a number, whatever.

var subitem1:NativeMenuItem = new NativeMenuItem("Red");
subitem1.data = "Whoop";
var subitem2:NativeMenuItem = new NativeMenuItem("Blue");
subitem2.data = 123;
var subitem3:NativeMenuItem = new NativeMenuItem("Green");
subitem3.data = ["array","values"];

And then we would trace that information on click like this:

function selectItem(evt:Event):void
{
trace("You've pressed the " + evt.target.label + " menu item, which has a data value of " + evt.target.data);
}

Here is the full code:

import flash.display.NativeMenu;
import flash.display.NativeMenuItem;
import flash.events.Event;

var myMenu:NativeMenu = new NativeMenu();

if (NativeWindow.supportsMenu)
{
stage.nativeWindow.menu = myMenu;
}
if (NativeApplication.supportsMenu)
{
NativeApplication.nativeApplication.menu = myMenu;
}

var item:NativeMenuItem = new NativeMenuItem("Hello!");
myMenu.addItem(item);

var mySubMenu:NativeMenu = new NativeMenu();
var subitem1:NativeMenuItem = new NativeMenuItem("Red");
subitem1.data = "Whoop";
var subitem2:NativeMenuItem = new NativeMenuItem("Blue");
subitem2.data = 123;
var subitem3:NativeMenuItem = new NativeMenuItem("Green");
subitem3.data = ["array","values"];
mySubMenu.addItem(subitem1);
mySubMenu.addItem(subitem2);
mySubMenu.addItem(subitem3);

item.submenu = mySubMenu;

subitem1.addEventListener(Event.SELECT, selectItem);
subitem2.addEventListener(Event.SELECT, selectItem);
subitem3.addEventListener(Event.SELECT, selectItem);

function selectItem(evt:Event):void
{
trace("You've pressed the " + evt.target.label + " menu item, which has a data value of " + evt.target.data);
}

Thanks for reading.

Related:

Working with menus in AIR: Part 1
Working with menus in AIR: Part 2
Working with menus in AIR: Part 4
Working with menus in AIR: Part 5
Working with menus in AIR: Part 6

No comments:

Post a Comment