Friday, April 8, 2011

Working with menus in AIR: Part 1

Today we will start learning how to make your own menus for your AIR applicationf or Windows operating system.

To create a menu, you first need to create a NativeMenu object.

var myMenu:NativeMenu = new NativeMenu();

Now we need to specify which window do we want to apply it to. We use the 'menu' property of the nativeWindow object (in this example it is the main window) to do that:

stage.nativeWindow.menu = myMenu;

Now, let's add a menu item. We can do that by simply creating a NativeMenuItem object and passing the label as a string value as the parameter:

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

And we need to add the item to our menu:

myMenu.addItem(item);

And it works!

Now, we have a bar on top of our AIR application with one button with "Hello!" on it. When we click a menu item, a submenu should open.

Create a nwe NativeMenu object to store all the information for your submenu. In this example it will be a menu of 3 items, labeled "Red", "Blue" and "Green".

var mySubMenu:NativeMenu = new NativeMenu();
var subitem1:NativeMenuItem = new NativeMenuItem("Red");
var subitem2:NativeMenuItem = new NativeMenuItem("Blue");
var subitem3:NativeMenuItem = new NativeMenuItem("Green");
mySubMenu.addItem(subitem1);
mySubMenu.addItem(subitem2);
mySubMenu.addItem(subitem3);

And now we apply this submenu to our "Hello!" item:

item.submenu = mySubMenu;

Full code:

import flash.display.NativeMenu;
import flash.display.NativeMenuItem;

var myMenu:NativeMenu = new NativeMenu();
stage.nativeWindow.menu = myMenu;

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

var mySubMenu:NativeMenu = new NativeMenu();
var subitem1:NativeMenuItem = new NativeMenuItem("Red");
var subitem2:NativeMenuItem = new NativeMenuItem("Blue");
var subitem3:NativeMenuItem = new NativeMenuItem("Green");
mySubMenu.addItem(subitem1);
mySubMenu.addItem(subitem2);
mySubMenu.addItem(subitem3);

item.submenu = mySubMenu;

Thank you for reading!

Related:

Working with menus in AIR: Part 2
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