Creating a segmented control

How to

Create a segmented control in your application.

Solution

Construct the segmented control variable in the root of your class

private var mySegment:SegmentedControl = new SegmentedControl(); 	
// Placing this at the class root allows other 
// application elements to reference it.

Initialize your control's attributes

// Location and size
mySegment.x = 10;
mySegment.y = 200;

// Set up array to store button data.
var buttonArray:Array=[]; 
buttonArray.push({label:"Mon"});
buttonArray.push({label:"Tues"});
buttonArray.push({label:"Thurs"});

// Create dataProvider for control to access data from array.
mySegment.dataProvider = new DataProvider(buttonArray);
// Add item to dataProvider at the end of the array.
mySegment.addItem({label: "Fri" });
// Add item to dataProvider at specific location.
mySegment.addItemAt({label: "Wed" }, mySegment.dataProvider.length -2);

// Call newChoiceMade function when button is clicked.
mySegment.addEventListener(Event.CHANGE, newChoiceMade);

// Add check box to stage.
this.addChild(mySegment);

Create the function that is called by your control's click event

private function newChoiceMade( e:Event ):void{
   // Output to console currently selected index.
   trace("Selected item " + mySegment.selectedIndex);		
}

Build requirements

You must include the following classes in your project:

import qnx.fuse.ui.buttons.SegmentedControl;
import qnx.ui.data.DataProvider;
import flash.events.Event;

Discussion

When you create a segmented control, you declare the SegmentedControl variable and then set its attributes. During initialization, you should assign a dataProvider to your control using the dataProvider function. This feature allows your control to be populated with the contents of the array assigned to the dataProvider, and allows you to manipulate the data within that array using functions such as addItem(), removeItem(), and replaceItem(). To add functionality, add an Event.CHANGE listener function to perform any actions that are defined in the function when the control is clicked. You can also query which element is currently selected in the segmented control by checking the selectedIndex property.

comments powered by Disqus