1. Trang chủ
  2. » Công Nghệ Thông Tin

O’Reilly Programming Flex 2 phần 4 potx

46 363 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề O’Reilly Programming Flex 2 phần 4 potx
Trường học O’Reilly Media
Chuyên ngành Programming
Thể loại Tài liệu hướng dẫn
Định dạng
Số trang 46
Dung lượng 320,9 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

For example, when the user clicks on a button, a click eventoccurs, and when the user expands a drop-down menu a combo box component,an open event occurs.. For example, but-tons dispatch

Trang 1

The scale of the component in the vertical direction relative to its original height.ThescaleYandheightproperties are linked just as thescaleXandwidthproper-ties are linked The values for scaleY are on the same range as are those forscaleX And you can both read and write thescaleY property

rotation

The number of degrees of rotation of the component relative to its original tation Rotation is always clockwise and is always relative to the origin point ofthe component’s internal coordinate system In almost all cases, a component’sorigin exists at the upper-left corner You can both read and write therotationproperty

orien-alpha

The opacity of the component The default value is 1, which means the nent is fully opaque The effective range for alpha is from 0 (transparent) to 1(opaque) You can read and write thealpha property

compo-visible

The visibility of the component The default value istrue, meaning the nent is visible A value offalse means the component is not visible You canboth read and write thevisible property

compo-enabled

Whether a component is interactive For example, if a button is enabled, it canaccept mouse clicks The default value istrue A value offalsedisables the com-ponent You can both read and write theenabled property

parent

A reference to the parent container for the component Theparent property isread-only If you want to change the parent of a component, you must use theremoveChild( )method of the parent container to remove the component or useaddChild( ) to add the component to a new container

The preceding list is not intended to be comprehensive by any means However, itdoes represent some of the most commonly used properties of all UI components.You can work with most of these properties both in MXML and in ActionScript(except when a property is read-only, in which case you must use ActionScript toread the value) The following example sets several properties of a button instanceusing MXML:

<mx:Button id="button" label="Example Button"

width="200" height="50" enabled="false" />

Here’s the equivalent ActionScript code:

var button:Button = new Button( );

button.label = "Example Button";

button.width = 200;

button.height = 50;

Trang 2

with the application For example, when the user clicks on a button, a click eventoccurs, and when the user expands a drop-down menu (a combo box component),

an open event occurs On the other hand, a system event occurs because somethinghappens within the application in response to initialization, asynchronous opera-tions, or other such nonuser-driven behavior For example, when a component iscreated, several events occur during the stages of creation indicating that variousaspects of the component are accessible

When an event occurs, we say that the event is dispatched (or broadcasted) The object that dispatches an event is called the target All Flex UI components are

potential event targets, meaning all UI components dispatch events The event thatgets dispatched is in the form of an object of typeflash.events.Event(or a subtype).TheEventinstance provides information about the event, including the type of event(click, open, etc.) and the target that dispatched the event

When a component dispatches an event, nothing occurs in response unless thing (called a listener) is configured to receive notifications There are two ways thatyou can handle events in a Flex application: one uses MXML attributes and the otheruses ActionScript

some-As you saw in Figure 7-1, all UI components inherit from the Flash

Player EventDispatcher class, meaning that all UI components can

dis-patch events to listeners.

Handling events with MXML

When you create a component using MXML, you can add an event handler using anattribute that has the same name as the event you want to handle For example, but-tons dispatch click events when the user clicks on them Therefore, you can add aclick attribute to the Button tag to handle the click event You also can assignActionScript to the attribute For example, the following code lowers the alpha by 1

of the button each time the user clicks on it:

<mx:Button id="button" label="Alpha Button" click="button.alpha -= 1" />

Although you can assign ActionScript expressions to event handler attributes, as inthe preceding example, it is more common (and useful) to assign a function call tothe event handler attribute This allows you to define more complex functionality inresponse to the event When you call a function/method from an event handler

Trang 3

attribute, you should pass a parameter called eventto the function In MXML, theevent parameter will automatically pass along the event object that the componentdispatches:

<mx:Button id="button" label="Alpha Button" click="clickHandler(event)" />

You then need to define the method that is intended to handle the event The methodshould accept a parameter of typeEvent(or the appropriate subtype) The followingexample accomplishes the same thing as the inline expression did previously How-ever, in addition, it resets the alpha to 1 if and when the alpha is less than 0:

private function clickHandler(event:Event):void {

var target:Button = Button(event.target);

Handling events with ActionScript

You can use ActionScript to add event listeners to a component as an alternative tousing MXML event attributes This is advantageous for several reasons First, it isuseful to add event listeners with ActionScript when you are creating the componentinstance using ActionScript as opposed to MXML Second, when you add event lis-teners using ActionScript, you can also remove the event listeners later This is handy

if you want to temporarily or permanently stop listening for a specific event for acomponent

In order to register a listener for an event using ActionScript you should employ theaddEventListener( ) method This method requires that you pass it at least twoparameters: the name of the event for which you want to listen and the function touse as the listener Typically, you should use constants for event names rather thanquoted strings to avoid typos that would introduce bugs that would not be caught bythe compiler The event name constants are members of the associated event class.For example, theEventclass definesOPEN,CLOSE,SCROLL,SELECT, and many other con-stants The MouseEvent class defines CLICK, MOUSE_OVER, and other mouse-relatedevent constants TheFlexEventclass defines constants for many of the Flex-specificevents such as ADD, REMOVE, CREATION_COMPLETE, and INITIALIZE The following codecreates a button and then adds a listener for the click event:

var button:Button = new Button( );

Trang 4

Event objects always have a type property that indicates the type of event the objectrepresents For example, a click event dispatches an object with a type property ofclick Event objects also have target properties that reference the actual object whichdispatched the event In some cases, the target may not be the object for which youhave registered a listener This can occur when the object for which you have regis-tered a listener contains a child component that also dispatches the same event (andthe event bubbles) If you want to ensure that you are getting a reference to theobject for which the listener is registered to listen for the event, use thecurrentTarget property.

Standard Flex component events

Each UI component type may have events that are specific to that type For ple, combo boxes dispatch open events when the menu is expanded However, all UIcomponents have a set of events in common Table 7-2 lists these common events

exam-The list of common events in Table 7-2 is not comprehensive exam-TheUIComponentclass(from which all UI components inherit) defines many more events For a comprehen-sive list, look at the Flex documentation listing formx.core.UIComponent We’ll also

Table 7-2 Common UI component events

remove FlexEvent.REMOVE The component has been removed from a container.

property is now true).

hide FlexEvent.HIDE The component has been made nonvisible (the

visi-ble property is now false).

preinitialize FlexEvent.PREINITIALIZE The component has started to initialize, but children

haven’t yet been created.

initialize FlexEvent.INITIALIZE The component has been constructed, but it has not

yet been measured and laid out.

creationComplete FlexEvent.CREATION_COMPLETE The component is completely created, measured,

and laid out.

Trang 5

discuss many of the events in this book in the sections for which they are mostappropriate (e.g., we discuss drag and drop events in the drag and drop section ofChapter 10).

Buttons

There are four basic button types of controls:Button, LinkButton,RadioButton, andCheckBox Although each type behaves similarly, they have different intended uses.Figure 7-2 shows instances of each type

Of the four types,ButtonandLinkButtonare the most similar in use In fact, the mary difference betweenButtonandLinkButtonis purely cosmetic: buttons have bor-ders and backgrounds, and link buttons do not However, you’ll typically use bothtypes for similar purposes—generally to initiate some behavior when the user clicks

pri-on the buttpri-on or link buttpri-on Buttpri-ons are typically more commpri-on than link buttpri-ons.With buttons and link buttons, the default behavior is that they respond to everyclick in the same way However, you can set the toggle property of a button or linkbutton to true, in which case the button will have two states—selected and dese-lected—and it will toggle between those states each time the user clicks it

Radio buttons are quite different in use from standard buttons Radio buttons aretypically used in groups Radio buttons can be selected or deselected, and only onebutton can be selected per group For this reason, radio buttons are often used whenyou want to allow the user to select just one from a group of options You shouldtypically first create a RadioButtonGroup instance when using radio buttons Then,assign the ID of the group to the groupName property of each radio button in thegroup, as shown here:

<mx:RadioButtonGroup id="exampleGroup" />

<mx:RadioButton groupName="exampleGroup" label="A" value="a" />

<mx:RadioButton groupName="exampleGroup" label="B" value="b" />

Checkboxes are also buttons They are most similar to standard buttons that havebeen set to toggle When a user clicks a checkbox, it toggles the selected state of thecomponent

Figure 7-2 Button components

Trang 6

Value Selectors

Value selectors are components that allow the user to select a value This is a fairly

diverse category of components because the types of values they allow the user toselect and the ways in which they allow the user to select the values are quite differ-ent Figure 7-3 shows the basic value selector components (except for VSlider,because it is the vertical version ofHSlider, which is shown)

The slider components (HSliderandVSlider) differ only in that one is horizontal andone is vertical Otherwise, they behave identically The slider components allow theuser to select a numeric value along a range from a minimum to a maximum value.The default range is 0 to 10, but you can adjust the range using the minimum andmaximum properties The slider components allow the user to drag a thumb alongthat range Optionally, you can add more than one thumb and allow the user toselect a range of values

The numeric stepper control allows the user to select a numeric value as well ever, the interface for a numeric stepper is quite different from that of a slider inter-face Where a slider interface is very graphical, the numeric stepper interface actuallydisplays the current numeric value in digits, allowing the user to scroll through thelist of possible values in the range

How-The color picker component is very useful for allowing the user to select a colorvalue from an expandable/collapsible grid of color swatches

The date field and date chooser components are useful because they allow the user toselect date values The date field component enables the user to select a single date in

Figure 7-3 Value selector components

Trang 7

a compact form Although the date field component expands to display a calendarwhile the user is selecting a date, it again collapses to a compact form once the userhas selected a value The date chooser component, on the other hand, is anexpanded format component that always displays the calendar from which the usercan select a date The date chooser component also allows the user to select multipledates and ranges of dates.

Trang 8

The label and text components are display-only components The user cannot editthe contents of either of these types The label component is useful for displayingone line of text, whereas the text component is useful for displaying multiple lines oftext.

The text input, text area, and rich text editor components are user input text trols The text input component allows the user to input one line of text The textarea component allows the user to input multiple lines of text, and it automaticallyadds scrollbars when necessary The rich text editor component not only allows theuser to input multiple lines of text, but it also allows her to apply formatting stylessuch as bold, italic, underline, text align, etc

con-List-Based Controls

List-based controls are some of the most sophisticated of the standard controls.These are the components that allow the user to select an item or items from a list ofoptions In the simplest form, a list might be a vertical, scrollable list of text labelsfrom which the user can select However, list-based controls can be increasinglycomplex from there, supporting columns, horizontal and grid-based layout, hierar-chical and collapsible structures, and even icons, images, and more Figure 7-5 showsthe list-based controls

The most fundamental of all the list-based controls is the list Such lists are vertically

scrolling, single-column controls

Horizontal lists are identical to standard lists except that they scroll horizontally

rather than vertically Horizontal lists are typically useful for scrolling icons and/orimages (thumbnails), though you could also use a horizontal list for simple text

Combo boxes are lists that collapse to a single line when not activated These types of controls are often referred to by users as drop-down menus, and they allow the user

to select from a vertically scrolling list of options when in an expanded state Once avalue has been selected, the control returns to the collapsed state

Tile lists are scrollable lists in which the contents are arranged in a grid Tile lists are

useful when you want to display contents in a grid, but you need the grid to scroll

Data grids are vertically scrolling, multicolumn lists Data grids are good for

display-ing data that consists of records of multiple values that a user might need to see atthe same time For example, a data grid would be a good choice for displaying thedetails of a user’s phone use history in which each row displays the time, the dura-tion, and the destination phone number, each in a different column (see Figure 7-5)

Tree controls are hierarchical types of lists They are very similar to standard lists

because they vertically scroll However, where standard lists have linear data els, trees have hierarchical data models in which individual elements can expand andcollapse to reveal and hide nested elements

Trang 9

mod-When you work with a list you always need a data provider A data provider is the

data model for which the list is the view All list-based components have adataProviderproperty you can use to assign the data model or retrieve a reference tothe current data model

Figure 7-5 List-based controls

Trang 10

UI components have a data property as well as a dataProvider

prop-erty Although it is easy enough to initially confuse the two, they are

different properties with different purposes The dataProvider

prop-erty allows you to set the data model for a component The data

prop-erty is used only when using a component as an item renderer for a

list-based component, as discussed in Chapter 8.

Data Models

Flex controls use model-view-controller, a software pattern that differentiatesbetween the display of data and the data itself This is very evident in the list-basedcontrols All list-based controls utilize data models In the language used by these

components, the data models are called data providers are independent objects

which you can associate with a control The control then uses that object’s data torender its view

Data providers always implement the mx.collections.ICollectonView interface.Although you can assign an array or anXMLobject to thedataProviderproperty ofmost list-based components, Flex converts the object behind the scenes to a typethat implements ICollectionView That means that arrays get converted to a typecalledmx.collections.ArrayCollectionandXMLandXMLListobjects get converted tomx.collections.XMLListCollection It’s generally best to always explicitly wrap theobject as a collection first before assigning it as the data provider That way you areassured of having a reference to the actual data provider collection rather than theobject wrapped by the collection

Creating a Collection Object

There are two basic ways to create collections: using ActionScript and using MXML.The ActionScript solution involves creating a new collection type, typically with theconstructor The following ActionScript example creates a new ArrayCollectionobject that wraps an array:

var collection:ICollectionView = new ArrayCollection(["a", "b", "c", "d"]);

Note that the variables in these examples are typed as ICollectionView

rather than the concrete types (e.g., ArrayCollection ) so that

polymor-phism can be utilized in later examples In the case of the preceding

example, you could technically type the variable as ArrayCollection

Likewise, this ActionScript example creates an XMLListCollection that wraps anXMLList object:

var xmlList:XMLList = <items><item>a</item><item>b</item>

<item>c</item><item>d</item></items>;

var collection:ICollectionView = new XMLListCollection(xmlList);

Trang 11

You can create the same collections using MXML The following example creates anArrayCollection object using MXML:

Setting the Data Provider

You can use any sort of collection (as long as it implements ICollectionView) withany sort of list-based control, allowing for versatile data structures All you have to

do is set thedataProviderproperty of the list-based control to be equal to the tion For example, the following uses anArrayCollection to populate a list:

collec-var collection:ICollectionView = new ArrayCollection(["a", "b", "c", "d"]);

<mx:List id="list" width="100">

<mx:ArrayCollection>

<mx:Array>

<mx:String>a</mx:String>

<mx:String>b</mx:String>

Trang 12

Using Data Grids

The preceding examples illustrated how to work with simple list-based controls such

as lists, combo boxes, tile lists, and horizontal lists Data grids inherit from standardlists, and therefore they function in much the same way However, because datagrids are more complex than standard lists, they have behavior that is specific tothem In the following sections, we’ll look at working with data grids

Using data providers

Data grid data providers are quite similar to standard data providers except that eachelement of a data grid data provider should consist of an object whose propertiescorrespond to the columns of the data grid The following example creates a data

grid with columns named city, state, and population:

<mx:DataGrid>

<mx:ArrayCollection>

<mx:Array>

<mx:Object city="Los Angeles" state="CA" population="3844829" />

<mx:Object city="New York" state="NY" population="8143197" />

<mx:Object city="Chicago" state="IL" population="2842518" />

<mx:Object city="Philadelphia" state="PA" population="1463281" />

private function creationCompleteHandler(event:Event):void {

var array:Array = new Array({city: "Los Angeles",

state: "CA", population: 3844829},

{city: "New York", state: "NY",

Trang 13

Working with data grid columns

By default, data grids automatically display columns corresponding to all the ties of the data provider elements The code in the preceding section creates a datagrid with three columns with the headings city, state, and population Althoughthis may be the intended behavior, in many cases it is not very versatile For this rea-son, it is possible to explicitly control the columns of a data grid

proper-You can specify which columns will display within a data grid by setting thecolumnsproperty of the data grid to an array ofDataGridColumn objects Using these columnobjects, you can filter which columns get displayed, the widths of the columns, theeditability of the columns, the heading text for the columns, and more Here’s anexample that displays the city and population values with custom labels, but doesnot display the state data:

<mx:DataGrid width="500">

<mx:columns>

<mx:DataGridColumn headerText="City" dataField="city" />

<mx:DataGridColumn headerText="Population (within city limits)"

dataField="population" />

</mx:columns>

<mx:ArrayCollection>

<mx:Array>

<mx:Object city="Los Angeles" state="CA" population="3844829" />

<mx:Object city="New York" state="NY" population="8143197" />

<mx:Object city="Chicago" state="IL" population="2842518" />

<mx:Object city="Philadelphia" state="PA" population="1463281" />

</mx:Array>

</mx:ArrayCollection>

</mx:DataGrid>

Using Tree Controls

Like data grids, tree controls inherit from standard lists but have specialized ior In the case of trees, the specialized behavior is that trees can render hierarchicaldata providers

behav-Although most lists display a linear list of elements (whether vertically, horizontally,

or in grid format), tree controls allow you to render elements that themselves have

nested child elements These sorts of data providers are called hierarchical data providers The following simple XML snippet demonstrates a hierarchical relation-

ship in which the cities are child elements of states:

Trang 14

<state label="CA">

<city label="Los Angeles" />

<city label="San Francisco" />

ele-<mx:Tree labelField="@label" width="200">

<mx:XMLListCollection>

<mx:XMLList>

<state label="CA">

<city label="Los Angeles" />

<city label="San Francisco" />

indi-Although it’s easiest to visualize hierarchical relationships with XML, you are notrestricted to using XML-based data providers for trees You can use any sort of col-lection For example, you can use an ArrayCollection object as a data provider.However, when you want to establish hierarchical relationships using collectiontypes that aren’t intrinsically hierarchical, you must follow certain rules Specifically,

in order to add children to an element, you must add them as an array for a propertycalled children The following example illustrates this using the city/state examplefrom before:

<mx:Tree labelField="label" width="200">

<mx:ArrayCollection>

<mx:Array>

<mx:Object label="CA">

<mx:children>

<mx:Object label="Los Angeles" />

<mx:Object label="San Francisco" />

</mx:children>

</mx:Object>

<mx:Object label="MA">

<mx:children>

Trang 15

private function creationCompleteHandler(event:Event):void {

var xmlList:XMLList = <items>

<item label="CA">

<item label="Los Angeles" />

<item label="San Francisco" />

private function creationCompleteHandler(event:Event):void {

var array:Array = new Array({label: "CA", children: new Array( {label: "Los Angeles"},

{label: "San Francisco"})},

{label: "MA", children: new Array( {label: "Boston"})});

var collection:ArrayCollection = new ArrayCollection(array);

tree.dataProvider = collection;

Trang 16

Working with Selected Values and Items

List-based controls allow for programmatic and user selection of elements An cation may frequently need to be able to detect which item the user has selected Forthis purpose, list-based controls have the following properties:

appli-allowMultipleSelection

By default, lists allow for one selected item at a time By settingallowMultipleSelection totrue, a user can select more than one item at a time.value

The value of the selected item The value of thevalueproperty depends on thestructure of the data provider Because it has very strict requirements, in order toget predictable results, it is frequently better not to rely on thevalue property.selectedItem

The element from the data provider corresponding to the selected item in thelist This is a very predictable property because it will always be a referencerather than an interpretation That means that if the data provider is a collection

of strings, theselectedItemwill be a string, but if the data provider is a tion of XML elements, theselectedItem will be an XML element

provid-of the rest provid-of the control’s elements

Trang 17

<mx:DataGridColumn headerText="City" dataField="city" />

<mx:DataGridColumn headerText="Population (within city limits)"

<mx:Object city="Chicago" state="IL" population="2842518" />

<mx:Object city="Philadelphia" state="PA" population="1463281" /> </mx:Array>

var menu:Menu = new Menu( );

var xmlList:XMLList = <items>

<item label="ActionScript">

<item label="Class" />

Trang 18

private var _menu:Menu;

private function creationCompleteHandler(event:Event):void {

_menu = new Menu( );

var xmlList:XMLList = <items>

Trang 19

Using PopUpMenuButton

The PopUpMenuButton control simplifies associating a menu with a button by matically creating the menu when assigning a data provider to the button, as illus-trated in this example:

Figure 7-7 shows what this example looks like

Listening to Menu Events

Menu controls dispatchitemClickevents of typemx.events.MenuEventevery time theuser selects a menu item You can listen for the event directly from the menu usingActionScript andaddEventListener If using PopUpMenuButton, you can listen for theitemClickevent directly from the button, and you can even use MXML to listen forthe event, as illustrated in this example which changes the button label each time theuser selects a menu item:

Figure 7-6 PopUpButton

Figure 7-7 PopUpMenuButton

Trang 20

<mx:PopUpMenuButton id="button" labelField="@label"

Navigators are controls that allow users to navigate from screen to screen, page to

page, section to section, or option to option within a Flex application We can ther categorize navigator controls as follows: accordion, divided boxes, option bars,and view stacks

fur-Accordion Controls

The accordion control consists of two or more collapsible containers Only one ment within an accordion can be visible at a time The other elements in the accor-dion are collapsed so that only a title bar is visible Accordions are often good forprocesses that require several steps and allow the user to return to previous steps.For example, an accordion is useful when a user input form contains many sections.Rather than try to present all the sections at once, an accordion allows the user toview just one section at a time, making for a more manageable experience Figure 7-8shows an example of an accordion

ele-Creating accordions, like most other components in Flex, is quite simple ons act just like all standard containers in that you can nest child elements in MXML

Accordi-or useaddChild( )to add child elements using ActionScript In the case of ons all child elements should be containers themselves, and you should add alabelproperty to all accordion children Accordions use thelabelproperties of child ele-ments for the title bar, and also have the ability to display icons when the icon prop-erty is set Here’s an example :

accordi-<mx:Accordion>

<mx:Form label="Name" icon="@Embed(source='/firstStep.png')">

<mx:FormItem label="First Name">

<mx:TextInput id="first" />

</mx:FormItem>

Trang 21

<mx:FormItem label="Middle Name">

Button bars, link bars, and toggle button bars are ways to create horizontal or cal groups of buttons These controls provide a convenient way to group buttonstogether Furthermore, in the case of toggle button bars, you have the added behav-ior that only one of the toggle buttons can be selected at a time All button, link, andtoggle button bars use data providers Here’s an example that creates a toggle buttonbar:

Trang 22

View stacks allow you to group together a set of containers and display just one at a

time This is useful when you want to use a page/screen/section metaphor The est way to work with a view stack is to use the tab navigator control, which has view

easi-Figure 7-9 Option bars

Trang 23

stack behavior built in Here’s an example of a tab navigator with nearly the sameform contents used earlier in the accordion example:

You can use a view stack without having to use the tab navigator It simply requiresthat you first create the view stack with the child containers Then, assuming you use

a button bar, link bar, or toggle button bar, you can simply assign the view stack asthe data provider of the bar:

Ngày đăng: 06/08/2014, 08:22

TỪ KHÓA LIÊN QUAN

w