Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 46 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
46
Dung lượng
320,9 KB
Nội dung
124 | Chapter 7: Working with UI Components scaleY The scale of the component in the vertical direction relative to its original height. The scaleY and height properties are linked just as the scaleX and width proper- ties are linked. The values for scaleY are on the same range as are those for scaleX. And you can both read and write the scaleY property. rotation The number of degrees of rotation of the component relative to its original orien- tation. Rotation is always clockwise and is always relative to the origin point of the component’s internal coordinate system. In almost all cases, a component’s origin exists at the upper-left corner. You can both read and write the rotation property. alpha The opacity of the component. The default value is 1, which means the compo- nent is fully opaque. The effective range for alpha is from 0 (transparent) to 1 (opaque). You can read and write the alpha property. visible The visibility of the component. The default value is true, meaning the compo- nent is visible. A value of false means the component is not visible. You can both read and write the visible property. enabled Whether a component is interactive. For example, if a button is enabled, it can accept mouse clicks. The default value is true. A value of false disables the com- ponent. You can both read and write the enabled property. parent A reference to the parent container for the component. The parent property is read-only. If you want to change the parent of a component, you must use the removeChild( ) method of the parent container to remove the component or use addChild( ) to add the component to a new container. The preceding list is not intended to be comprehensive by any means. However, it does 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 to read the value). The following example sets several properties of a button instance using 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; Understanding UI Components | 125 button.enabled = false; addChild(button); Handling Events Events are the way in which objects (such as Flex UI components) can communicate with the rest of the application. There are two basic types of events: user events and system events. User events are events that occur directly because of user interaction with the application. For example, when the user clicks on a button, a click event occurs, 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 something happens within the application in response to initialization, asynchronous opera- tions, or other such nonuser-driven behavior. For example, when a component is created, several events occur during the stages of creation indicating that various aspects 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 that gets dispatched is in the form of an object of type flash.events.Event (or a subtype). The Event instance 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 some- thing (called a listener) is configured to receive notifications. There are two ways that you can handle events in a Flex application: one uses MXML attributes and the other uses ActionScript. 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 an attribute 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 a click attribute to the Button tag to handle the click event. You also can assign ActionScript 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 in the preceding example, it is more common (and useful) to assign a function call to the event handler attribute. This allows you to define more complex functionality in response to the event. When you call a function/method from an event handler 126 | Chapter 7: Working with UI Components attribute, you should pass a parameter called event to the function. In MXML, the event parameter will automatically pass along the event object that the component dispatches: <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 method should accept a parameter of type Event (or the appropriate subtype). The following example 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); target.alpha -= .1; if(target.alpha < 0) { target.alpha = 1; } } Handling events with ActionScript You can use ActionScript to add event listeners to a component as an alternative to using MXML event attributes. This is advantageous for several reasons. First, it is useful to add event listeners with ActionScript when you are creating the component instance 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 a component. In order to register a listener for an event using ActionScript you should employ the addEventListener( ) method. This method requires that you pass it at least two parameters: the name of the event for which you want to listen and the function to use as the listener. Typically, you should use constants for event names rather than quoted strings to avoid typos that would introduce bugs that would not be caught by the compiler. The event name constants are members of the associated event class. For example, the Event class defines OPEN, CLOSE, SCROLL, SELECT, and many other con- stants. The MouseEvent class defines CLICK, MOUSE_OVER, and other mouse-related event constants. The FlexEvent class defines constants for many of the Flex-specific events such as ADD, REMOVE, CREATION_COMPLETE, and INITIALIZE. The following code creates a button and then adds a listener for the click event: var button:Button = new Button( ); button.addEventListener(MouseEvent.CLICK, clickHandler); addChild(button); The event listener function is automatically passed an Event object as a parameter: private function clickHandler(event:MouseEvent):void { var target:Button = Button(event.target); target.alpha -= .1; if(target.alpha < 0) { Understanding UI Components | 127 target.alpha = 1; } } Event objects The flash.events.Event class is the base class for all events in Flex applications. However, many event objects are instances of event subtypes. For example, events related to mouse behavior ( click, mouseOver, etc.) are of type MouseEvent. Event objects always have a type property that indicates the type of event the object represents. For example, a click event dispatches an object with a type property of click. Event objects also have target properties that reference the actual object which dispatched the event. In some cases, the target may not be the object for which you have 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 (and the event bubbles). If you want to ensure that you are getting a reference to the object for which the listener is registered to listen for the event, use the currentTarget property. Standard Flex component events Each UI component type may have events that are specific to that type. For exam- ple, combo boxes dispatch open events when the menu is expanded. However, all UI components have a set of events in common. Table 7-2 lists these common events. The list of common events in Table 7-2 is not comprehensive. The UIComponent class (from which all UI components inherit) defines many more events. For a comprehen- sive list, look at the Flex documentation listing for mx.core.UIComponent. We’ll also Table 7-2. Common UI component events Event Constant Description add FlexEvent.ADD The component has been added to a container. remove FlexEvent.REMOVE The component has been removed from a container. show FlexEvent.SHOW The component has been made visible (the visible property is now true). hide FlexEvent.HIDE The component has been made nonvisible (the visi- ble property is now false). resize FlexEvent.RESIZE The component dimensions have changed. preinitialize FlexEvent.PREINITIALIZE The component hasstarted 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. 128 | Chapter 7: Working with UI Components discuss many of the events in this book in the sections for which they are most appropriate (e.g., we discuss drag and drop events in the drag and drop section of Chapter 10). Buttons There are four basic button types of controls: Button, LinkButton, RadioButton, and CheckBox. Although each type behaves similarly, they have different intended uses. Figure 7-2 shows instances of each type. Of the four types, Button and LinkButton are the most similar in use. In fact, the pri- mary difference between Button and LinkButton is purely cosmetic: buttons have bor- ders and backgrounds, and link buttons do not. However, you’ll typically use both types for similar purposes—generally to initiate some behavior when the user clicks on the button or link button. Buttons are typically more common than link buttons. With buttons and link buttons, the default behavior is that they respond to every click in the same way. However, you can set the toggle property of a button or link button 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 are typically used in groups. Radio buttons can be selected or deselected, and only one button can be selected per group. For this reason, radio buttons are often used when you want to allow the user to select just one from a group of options. You should typically 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 the group, 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 have been set to toggle. When a user clicks a checkbox, it toggles the selected state of the component. Figure 7-2. Button components Value Selectors | 129 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 to select 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 of HSlider, which is shown). The slider components ( HSlider and VSlider) differ only in that one is horizontal and one is vertical. Otherwise, they behave identically. The slider components allow the user 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 and maximum properties. The slider components allow the user to drag a thumb along that range. Optionally, you can add more than one thumb and allow the user to select a range of values. The numeric stepper control allows the user to select a numeric value as well. How- 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 actually displays the current numeric value in digits, allowing the user to scroll through the list of possible values in the range. The color picker component is very useful for allowing the user to select a color value from an expandable/collapsible grid of color swatches. The date field and date chooser components are useful because they allow the user to select date values. The date field component enables the user to select a single date in Figure 7-3. Value selector components 130 | Chapter 7: Working with UI Components a compact form. Although the date field component expands to display a calendar while the user is selecting a date, it again collapses to a compact form once the user has selected a value. The date chooser component, on the other hand, is an expanded format component that always displays the calendar from which the user can select a date. The date chooser component also allows the user to select multiple dates and ranges of dates. Text Components There are five basic text components that we can further categorize into display and input components. Figure 7-4 shows these components. Figure 7-4. Text components List-Based Controls | 131 The label and text components are display-only components. The user cannot edit the contents of either of these types. The label component is useful for displaying one line of text, whereas the text component is useful for displaying multiple lines of text. The text input, text area, and rich text editor components are user input text con- trols. The text input component allows the user to input one line of text. The text area component allows the user to input multiple lines of text, and it automatically adds scrollbars when necessary. The rich text editor component not only allows the user to input multiple lines of text, but it also allows her to apply formatting styles such as bold, italic, underline, text align, etc. 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 of options. In the simplest form, a list might be a vertical, scrollable list of text labels from which the user can select. However, list-based controls can be increasingly complex from there, supporting columns, horizontal and grid-based layout, hierar- chical and collapsible structures, and even icons, images, and more. Figure 7-5 shows the 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/or images (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 a value 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 at the same time. For example, a data grid would be a good choice for displaying the details 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 mod- els, trees have hierarchical data models in which individual elements can expand and collapse to reveal and hide nested elements. 132 | Chapter 7: Working with UI Components 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 a dataProvider property you can use to assign the data model or retrieve a reference to the current data model. Figure 7-5. List-based controls List-Based Controls | 133 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 differentiates between the display of data and the data itself. This is very evident in the list-based controls. 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 to render its view. Data providers always implement the mx.collections.ICollectonView interface. Although you can assign an array or an XML object to the dataProvider property of most list-based components, Flex converts the object behind the scenes to a type that implements ICollectionView. That means that arrays get converted to a type called mx.collections.ArrayCollection and XML and XMLList objects get converted to mx.collections.XMLListCollection. It’s generally best to always explicitly wrap the object as a collection first before assigning it as the data provider. That way you are assured of having a reference to the actual data provider collection rather than the object 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 the constructor. The following ActionScript example creates a new ArrayCollection object 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 an XMLList object: var xmlList:XMLList = <items><item>a</item><item>b</item> <item>c</item><item>d</item></items>; var collection:ICollectionView = new XMLListCollection(xmlList); [...]... Pop-Up Controls Apart from the ability to... dataField="population" /> Using Tree Controls Like data grids, tree controls... population: You can, of course, achieve the same result using... xmlns:mx="http://www.adobe.com /20 06/mxml" creationComplete="creationCompleteHandler(event)"> 844 829 }, {city: "New York", state: "NY", population: 8 143 197}, {city: "Chicago", state: "IL", population: 28 42 5 18}, {city: "Philadelphia",... D Figure 7- 12 shows what this looks like 148 | Chapter 7: Working with UI Components Figure 7- 12 Application control bars docked so that they don’t scroll with the rest of the content Summary In... get started working with user interface controls in Flex 2 We discussed event handling with controls, and we provided an overview of all the major types of standard UI controls, from buttons to lists to control bars Summary | 149 Chapter 8 8 CHAPTER Framework Utilities and Advanced Component Concepts 8 As you’ve already learned in earlier chapters, the Flex framework provides a large library of components,... Pop-Ups The Flex framework has built-in support for pop-up windows and alerts Pop ups can be useful for many reasons, including notifying the user of messages or news and displaying simple forms such as login forms or mailing-list sign-up forms Unlike HTML pop ups, Flex pop ups do not open new browser windows Flex application pop ups appear within the same Flash Player instance This means that Flex application... property to true to dock the control panel such that it does not scroll Here’s how you would do that: A... panel You can then place controls within the control bar Here’s an example: ... the new Alert instance that you can use to manipulate the Alert instance if needed Example 8 -2 displays an alert with a message and an OK button (the default behavior) when the user clicks a button Example 8 -2 Using alerts . "CA", population: 3 844 829 }, {city: "New York", state: "NY", population: 8 143 197}, {city: "Chicago", state: "IL", population: 28 42 5 18}, {city: "Philadelphia",. city="Chicago" state="IL" population=" ;28 42 5 18" /> <mx:Object city="Philadelphia" state="PA" population=" 146 328 1" /> </mx:Array> </mx:ArrayCollection> </mx:DataGrid> You. city="Chicago" state="IL" population=" ;28 42 5 18" /> <mx:Object city="Philadelphia" state="PA" population=" 146 328 1" /> </mx:Array> </mx:ArrayCollection> </mx:DataGrid> Using