You can load style sheets at run time by using the StyleManager. These style sheets take the form of SWF files that are dynamically loaded while your Flex application runs.
By loading style sheets at run time, you can load images (for graphical skins), fonts, type and class selectors, and programmatic skins into your Flex application without embedding them at compile time. This lets skins and fonts be partitioned into separate SWF files, away from the main application. As a result, the application's SWF file size is smaller, which reduces the initial download time. However, the first time a run-time style sheet is used, it takes longer for the styles and skins to be applied than if you load styles by using the <mx:Style> tag. This is because Flex must download the necessary CSS-based SWF file while the application is starting up or running.
Loading style sheets at run time is a three-step process:
You can load multiple style sheets that define the same styles. After you set a style, subsequent style sheets can overwrite previous ones if they have common selectors. Styles loaded with run-time style sheets do not completely replace compile-time styles, however. They just override them until the run-time style sheets are unloaded. At that point, Flex reverts to the compile-time style settings. Compile-time style settings include any default styles sheets that were loaded at compile time, theme files loaded by using the theme compiler option, and styles set by using the <mx:Style> block inside an MXML file.
You cannot load an uncompiled CSS file into your Flex application at run time. You must compile it into a SWF file before loading it.
To load style sheets at run time, you must first create a style sheet that is compiled into a SWF file. A run-time style sheet is like any other style sheet. It can be a simple style sheet that sets basic style properties, as the following example shows:
/* styles/runtime/assets/BasicStyles.css */
Button {
fontSize: 24;
color: #FF9933;
}
Label {
fontSize: 24;
color: #FF9933;
}
Or the style sheet can be a complex style sheet that embeds programmatic and graphical skins, fonts, and other style properties, and uses type and class selectors, as the following example shows:
/* styles/runtime/assets/ComplexStyles.css */
Application {
backgroundImage: "greenBackground.gif";
theme-color: #9DBAEB;
}
Button {
fontFamily: Tahoma;
color: #000000;
fontSize: 11;
fontWeight: normal;
text-roll-over-color: #000000;
upSkin: Embed(source="orb_up_skin.gif");
overSkin: Embed(source="orb_over_skin.gif");
downSkin: Embed(source="orb_down_skin.gif");
}
.noMargins {
margin-right: 0;
margin-left: 0;
margin-top: 0;
margin-bottom: 0;
horizontal-gap: 0;
vertical-gap: 0;
}
To create a new style sheet in Flex Builder, you select File > New > CSS File. Create the CSS file in the project's main directory or another subdirectory that is not the bin directory. You should not create the CSS file in the bin directory. Flex Builder will compile the SWF file to the bin directory for you.
Before you can load a style sheet at run time, you must compile the style sheet into a SWF file. The style sheet that you compile into a SWF file must use a .css filename extension.
To compile the CSS file into a SWF file, you use the mxmlc command-line compiler or Flex Builder's compiler. The default result of the compilation is a SWF file with the same name as the CSS file, but with the .swf extension.
The following example produces the BasicStyles.swf file by using the mxmlc command-line compiler:
mxmlc BasicStyles.css
To compile the SWF file with Flex Builder, right-click the CSS file and select Compile CSS to SWF. Flex Builder saves the SWF file in the project's bin directory. If the original CSS file is in the bin directory, you cannot compile it into a SWF file. You must move it to a different directory before you can compile it.
When you compile your Flex application, the compiler does not perform any compile-time link checking against the CSS-based SWF files used by the application. This means that you are not required to create the SWF file before you compile your main application. This also means that if you mistype the name or location of the SWF file, or if the SWF file does not exist, the application will fail silently. The application will not throw an error at run time.
You load a CSS-based SWF file at run time by using the StyleManager's loadStyleDeclarations() method. To use this method, you must import the mx.core.StyleManager class.
The following example shows loading a style sheet SWF file:
StyleManager.loadStyleDeclarations("../assets/MyStyles.swf");
The first parameter of the loadStyleDeclarations() method is the location of the style sheet SWF file to load. The location can be local or remote.
The second parameter is update. You set this to true or false, depending on whether you want the style sheets to immediately update in the application. For more information, see Updating CSS-based SWF files.
The next parameter, trustContent, is optional and obsolete. If you do specify a value, set this to false.
The final two parameters are applicationDomain and securityDomain. These parameters specify the domains into which the style sheet SWF file is loaded. In most cases, you should accept the default values (null) for these parameters. The result is that the style sheet's SWF file is loaded into child domains of the current domains. For information on when you might use something other than the default for these parameters, see Using run-time style sheets with modules.
The following example loads a style sheet when you click the button:
<?xml version="1.0"?>
<!-- styles/BasicApp.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.styles.StyleManager;
public function applyRuntimeStyleSheet():void {
StyleManager.loadStyleDeclarations("../assets/BasicStyles.swf")
}
]]>
</mx:Script>
<mx:Label text="Click the button to load a new CSS-based SWF file"/>
<mx:Button id="b1" label="Click Me" click="applyRuntimeStyleSheet()"/>
</mx:Application>
The executing SWF file for the previous example is shown below:
Loading a remote style sheet typically requires a crossdomain.xml file that gives the loading application permission to load the SWF file. You can do without a crossdomain.xml file if your application is in the local-trusted sandbox, but this is usually restricted to SWF files that have been installed as applications on the local machine. For more information about crossdomain.xml files, see Using cross-domain policy files.
Also, to use remote style sheets, you must compile the loading application with network access (have the use-network compiler property set to true, the default). If you compile and run the application on a local file system, you might not be able to load a remotely accessible SWF file.
The loadStyleDeclarations() method is asynchronous. It returns an instance of the IEventDispatcher class. You can use this object to trigger events based on the success of the style sheet's loading. You have access to the StyleEvent.PROGRESS, StyleEvent.COMPLETE, and StyleEvent.ERROR events of the loading process.
The following application calls a method when the style sheet finishes loading:
<?xml version="1.0"?>
<!-- styles/StylesEventApp.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.styles.StyleManager;
import mx.events.StyleEvent;
public function init():void {
var myEvent:IEventDispatcher =
StyleManager.loadStyleDeclarations("../assets/ACBStyles.swf");
myEvent.addEventListener(StyleEvent.COMPLETE, getImage);
}
private function getImage(event:StyleEvent):void {
map1.source = acb.getStyle("dottedMap");
}
]]>
</mx:Script>
<mx:ApplicationControlBar id="acb" width="100%" styleName="homeMap">
<mx:Image id="map1"/>
<mx:Button label="Submit"/>
</mx:ApplicationControlBar>
</mx:Application>
The executing SWF file for the previous example is shown below:
The style sheet used in this example embeds a PNG file:
/* styles/runtime/assets/ACBStyles.css */
ApplicationControlBar {
borderStyle: "solid";
cornerRadius: 10;
backgroundColor: #FF9933;
alpha: 1;
dottedMap: Embed(source="beige_dotted_map.png");
}
You can force an immediate update of all styles in the application when you load a new CSS-based SWF file. You can also delay the update if you want.
The second parameter of the loadStyleDeclarations() method is update. Set the update parameter to true to force an immediate update of the styles. Set it to false to avoid an immediate update of the styles in the application. The styles are updated the next time you call this method or the unloadStyleDeclarations() method with the update property set to true.
Each time you call the loadStyleDeclarations() method with the update parameter set to true, Adobe® Flash Player and Adobe AIR™ reapply all styles to the display list, which can degrade performance. If you load multiple CSS-based SWF files at the same time, you should set the update parameter to false for all but the last call to this method. As a result, Flash Player and AIR apply the styles only once for all new style SWF files rather than once for each new style SWF.
The following example loads three style SWF files, but does not apply them until the third one is loaded:
<?xml version="1.0"?>
<!-- styles/DelayUpdates.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.styles.StyleManager;
import mx.events.StyleEvent;
public function init():void {
StyleManager.loadStyleDeclarations("../assets/ButtonStyles.swf", false);
var myEvent:IEventDispatcher =
StyleManager.loadStyleDeclarations("../assets/LabelStyles.swf", false);
myEvent.addEventListener(StyleEvent.COMPLETE, doUpdate);
}
public function doUpdate(event:StyleEvent):void {
StyleManager.loadStyleDeclarations("../assets/ACBStyles.swf", true);
}
]]>
</mx:Script>
<mx:Label text="This is a label."/>
<mx:ApplicationControlBar id="acb" width="100%">
<mx:Button label="Submit"/>
</mx:ApplicationControlBar>
</mx:Application>
The executing SWF file for the previous example is shown below:
You can unload a style sheet that you loaded at run time. You do this by using the StyleManager's unloadStyleDeclarations() method. The result of this method is that all style properties set by the specified style SWF files are returned to their defaults.
The following example loads and unloads a style SWF when you toggle the check box:
<?xml version="1.0"?>
<!-- styles/UnloadStyleSheets.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.styles.StyleManager;
public function toggleStyleSheet():void {
if (cb1.selected == true) {
StyleManager.loadStyleDeclarations("../assets/ButtonStyles.swf", true);
StyleManager.loadStyleDeclarations("../assets/LabelStyles.swf", true);
} else {
StyleManager.unloadStyleDeclarations("../assets/ButtonStyles.swf", true);
StyleManager.unloadStyleDeclarations("../assets/LabelStyles.swf", true);
}
}
]]>
</mx:Script>
<mx:Button id="b1" label="Click Me"/>
<mx:Label id="l1" text="Click the button"/>
<mx:CheckBox id="cb1"
label="Load style sheet"
click="toggleStyleSheet()"
selected="false"
/>
</mx:Application>
The executing SWF file for the previous example is shown below:
The unloadStyleDeclarations() method takes a second parameter, update. As with loading style sheets, Flash Player and AIR do not reapply the styles (in this case, reapply default styles when the loaded styles are unloaded) if you set the value of the update parameter to false. For more information about the update parameter, see Loading style sheets at run time.
You can use run-time style sheets in custom components. To do this, you generally call the loadStyleDeclaration() method after the component is initialized. If the style sheet contains class selectors, you then apply them by setting the styleName property.
The following example defines style properties and skins in a class selector named specialStyle:
/* styles/runtime/assets/CustomComponentStyles.css */
.specialStyle {
fontSize: 24;
color: #FF9933;
upSkin: Embed(source="SubmitButtonSkins.swf", symbol="MyUpSkin");
overSkin: Embed(source="SubmitButtonSkins.swf", symbol="MyOverSkin");
downSkin: Embed(source="SubmitButtonSkins.swf", symbol="MyDownSkin");
}
The following example custom component loads this style sheet and applies the specialStyle class selector to itself during initialization:
// styles/runtime/MyButton.as -->
package {
import mx.controls.Button;
import mx.events.*;
import mx.styles.StyleManager;
public class MyButton extends Button {
public function MyButton() {
addEventListener(FlexEvent.INITIALIZE, initializeHandler);
}
// Gets called when the component has been initialized
private function initializeHandler(event:FlexEvent):void {
StyleManager.loadStyleDeclarations("../assets/CustomComponentStyles.swf");
this.styleName = "specialStyle";
}
}
}
The following sample application uses this custom button:
<?xml version="1.0"?> <!-- styles/MyButtonApp.mxml --> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:custom="*"> <custom:MyButton/> </mx:Application>The executing SWF file for the previous example is shown below:
If you have an existing theme SWC file, you can use it as a run-time style sheet. To do this, you must extract the CSS file from the theme SWC file. You then compile the style SWF file by passing the remaining SWC file as a library.
The following steps show this process using the command line:
$ unzip haloclassic.swc defaults.css
$ mv defaults.css haloclassic.css
$ mxmlc -include-libraries=haloclassic.swc haloclassic.css
If you have multiple CSS files inside a theme SWC file, you must extract all of them before compiling the style SWF file.
You can use the StyleManager class in a module or child application just as you would use it in the main application. You can apply run-time style sheets that are loaded by modules to the main application as well as to the module. To do this, you must load the style sheet into the current application domain by specifying the applicationDomain parameter to be ApplicationDomain.currentDomain in the loadStyleDeclarations() method. The StyleManager is owned by the main application, so even though you are calling its methods from the module, the current application domain is the main application's domain.
The following example loads the Style.swf file in the module into the current application domain:
StyleManager.loadStyleDeclaration("Style.swf",true,false, ApplicationDomain.currentDomain)
By loading the SWF file into the same application domain, you can access its classes directly. In this case, by loading the run-time style sheet into the same application domain as the main application, the styles can be applied to the main application as well as the module.
The following example illustrates loading the run-time style sheet into a child application domain and the current application domain:
In the first approach, the module and the run-time style sheet are loaded into separate child application domains (application domains 2 and 3). The styles can be applied only to the applications within the parent domain and that child domain, so the styles will not be properly applied to the module, which is in a separate child domain. The second approach loads the module into a child application domain and the run-time style sheet into the same domain as the main application. In this case, the styles can be applied to the module and the main application properly.
The reason you must use the second approach is that the ModuleManager class is responsible for loading all modules, including CSS SWF files. This class is a Singleton that is defined by the main application. Even though you call methods on the ModuleManager from within the module, you are calling those methods from within the context of the main application. As a result, the default domain that the ModuleManager loads SWF files into is a child of the main application's domain and not a child domain of whatever SWF file the methods happen to be executed in.
Because SWF files in sibling application domains cannot communicate, styles loaded into one child application domain will not be applied properly to SWF files loaded into another child application domain. By specifying the ApplicationDomain.currentDomain in the loadStyleDeclarations() method, you instruct the ModuleManager to not load the CSS SWF file into a new child application domain, but instead to load it into the main application's application domain so it can be used by your main application and the module.
For more information about application domains, see Using the ApplicationDomain class.