Tuesday, January 27, 2009

Dynamic Styles in Flex

Loading CSS at Runtime:

Flex does have many features to offer. One of them, which really catches the eye, is the ability to load your CSS files at runtime.

For a UI intense application, deployed at multiple places a change in color schemes and a few skins could mean a complete copy of the entire project. Fortunately, with this [loading css at runtime] approach, things get a lot simpler.

What we need to do:

  1. Write a css file for your application .
  2. Compile the css file into swf. This can be done either via the command prompt by running the command in the path of the flex compiler mxmlc css_filename.css or by using the Flex Builder option "Compile CSS to SWF".
  3. The compiled file can be found in the output folder of your project.
  4. Load the style sheet in your code. This can be done via the appplication initialize event or in the code itself.
<mx:Application mx="http://www.adobe.com/2006/mxml" layout="absolute" creationcomplete="this.applyStyleSheet();" width=100%" height="90%">

<mx:script>
<![CDATA[

private function applyStyleSheet():void
{
/* You can also load the name of the file from the configuration or the DB. */
var styleSheetUrl:String = "file_path/filename.swf"
var event:IEventDispatcher = StyleManager.loadStyleDeclarations(url);
event.addEventListener(StyleEvent.COMPLETE,this.startInitProcess);
}

private function startInitProcess(event:StyleEvent):void
{
// Rest of the application code starts from here.
}

]]>
</mx:script>

</mx:Application>

The above code loads up the stylesheet from the specified path. The rest of the UI then loads up taking the styles as defined in your custom stylesheet.

Cheers and Happy Styling.

No comments :