创建状态
在许多 Rich Internet Application 中, 界面会根据用户正在执行的任务而变化。 当用户在图像上滚动鼠标时图像会发生变化, 这样的图像就是一个简单的示例。 许多复杂的示例包括其内容会根据用户在某个任务中的进度而变化的用户界面, 如从浏览视图更改到详细信息视图。 这些界面可以使用平滑的打开-关闭效果在视图之间过渡。
视图状态使您可以很容易地实施这样的行为, 并可以简化在其他方面复杂的事件处理代码的内容。
若要了解如何定义视图状态之间的过渡, 请参阅定义状态过渡 。
简单地说, 视图状态定义组件的某个特定视图。 例如, 产品缩略图可以有两个视图状态;包含次要信息的基本状态和包含附加信息的富状态。 相似地, 应用程序可以有与不同应用程序状况相对应的多个视图状态, 如登录状态、概述状态或搜索结果状态。
下面的示例使用视图状态很容易地实现登录和注册表单。 在此示例中, 初始视图状态提示用户登录, 并会根据需要包含让他们注册的链接。 如果用户选择“需要注册”链接, 则该表单会改变视图状态以显示注册信息。 当用户单击“返回登录”链接时, 视图状态会变回到登录表单。
示例
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml " verticalAlign="middle"
width="340" height="250"
>
<!-- The states property of the Application class
defines the view states. -->
<mx:states>
<!--
The "Register" state is based on the base state.
All states are based on the base state by default
so you can leave out the basedOn property.
-->
<mx:State name="Register" basedOn=""><!-- Add a FormItem component to the form. -->
<mx:AddChild
relativeTo="{loginForm}"
position="lastChild"
creationPolicy="all"
><mx:FormItem id="confirm" label="Confirm:">
<mx:TextInput/>
</mx:FormItem>
</mx:AddChild>
<!-- Set properties on the Panel container and Button control. -->
<mx:SetProperty target="{loginPanel}"
name="title" value="Register"/>
<mx:SetProperty target="{loginButton}"
name="label" value="Register"/>
<!-- Remove the existing LinkButton control. --><mx:RemoveChild target="{registerLink}"/>
<!--
Add a new LinkButton control to change
view state back to the login form.
-->
<mx:AddChild relativeTo="{spacer1}" position="before"><mx:LinkButton label="Return to Login" click="currentState=''"/>
</mx:AddChild></mx:State>
</mx:states>
<mx:Panel
title="Login" id="loginPanel"
horizontalScrollPolicy="off" verticalScrollPolicy="off"
><mx:Form id="loginForm">
<mx:FormItem label="Username:">
<mx:TextInput/></mx:FormItem>
<mx:FormItem label="Password:">
<mx:TextInput/>
</mx:FormItem>
</mx:Form>
<mx:ControlBar>
<!--
Use the LinkButton control to change to
the Register view state.
-->
<mx:LinkButton
label="Need to Register?" id="registerLink"
click="currentState='Register'"
/><mx:Spacer width="100%" id="spacer1"/>
<mx:Button label="Login" id="loginButton"/>
</mx:ControlBar>
</mx:Panel>
</mx:Application>
结果
若要查看全部源代码, 请右键单击 Flex 应用程序并从上下文菜单中选择“查看源代码”。