Saturday, April 9, 2011

Working with menus in AIR: Part 2

In the last tutorial we've discussed how to create menus for AIR applications in Windows. Today we will learn how to make it also work on Mac OS.

The trick is, that unlike Windows, Mac OS doesn't have window menus, but it has application menus instead. This means that if we apply our NativeMenu object to stage.nativeWindow.menu, it will only work on Windows, but if we set it to NativeApplication.nativeApplication.menu, it will only work on Mac.

// For Windows:
stage.nativeWindow.menu = myMenu;

// For Mac OS:
NativeApplication.nativeApplication.menu = myMenu;

How to fix this? We can check, which of the two menu types does the user's OS support, and then apply our menu object to the nativeWindow on Windows or NativeApplication on Mac.

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

The rest of the code is the same on all platforms. Now that we have set our myMenu to what we needed to, we can work with the myMenu object and do whatever we want to it. So, if we combine the code from this tutorial and the code from the previous tutorial, we will get this:

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 3
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