Monday, April 11, 2011

Working with menus in AIR: Part 4

Today we will learn how to make checkable menu items in an AIR application.

Sometimes, there are toggle-like items in menus in softwares. For example, in Adobe Flash, there's a whole list of windows in a submenu of the Window menu - Components, Library, etc. You can check and uncheck those.

To do that toggling feature, we will need to use the checked property of a NativeMenuItem object. By default it is set to false and no icon is displayed next to the label in the menu. However, if we set it to true, you can see a 'check' sign next to the label:

myitem.checked = true;

However, if you set the checked property of an item to true and then try to run the code, you'll see that you can't uncheck the item. From the user side, that is. The checked property does not mean 'set this to true to make this a toggle switch', but rather 'set this to true to show the check icon'. But this is enough for us, because we can do the rest with our own code.

What we're going to do, is check if the item that the user clicks on is checked or not. If it is, then set checked to false, and vice versa.

Here's how the selectItem() function will look like then:

function selectItem(evt:Event):void
{
if (evt.target.checked)
{
trace("You've unchecked the " + evt.target.label + "key.");
evt.target.checked = false;
}
else
{
trace("You've checked the " + evt.target.label + "key.");
evt.target.checked = true;
}
}

You can now check-uncheck the items.

The final code is:

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");
var subitem2:NativeMenuItem = new NativeMenuItem("Blue");
var subitem3:NativeMenuItem = new NativeMenuItem("Green");
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
{
if (evt.target.checked)
{
trace("You've unchecked the " + evt.target.label + "key.");
evt.target.checked = false;
}
else
{
trace("You've checked the " + evt.target.label + "key.");
evt.target.checked = true;
}
}

Thanks for reading!

Related:

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

No comments:

Post a Comment