Changing Flex Style Sheets at runtime

Sorry its been so long since the last blog entry, between the two kids, writing 3 books, and many clients, its been hard to find time to write new entries here.  Today, I wanted to give a quick example of the Flex 2.0.1 feature of loading CSS style sheets at runtime.

In most Flex applications, I had been creating a seperate CSS style sheet, and compiling it into the application through the use of the <mx:Script source="…" />.  One of the pains of this, is that applying changes to the styles requires re-compiling the application, and as you probably now, the styles are one of the most frequently changed aspects of any application.

To help solve this problem, Adobe implemented the ability to load Style Sheets at run time in the Flex 2.0.1 release.  To do this, you first need to compile the CSS into a swf.  You can do this in FlexBuilder by right clicking on the css file and choosing "Compile CSS to SWF" option, or using the comand line compiler (mxmlc).  Once the css is compiled into a swf, it can be loaded with the StyleManager.loadStyleDeclarations(…) method.  Consider this simple example:

TestLoadStyles.mxml 

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
 <mx:Style>
  .text1{
   color:#0000ff;
  }
  .text2{
   color:#ffff00;
  }
 </mx:Style>
 <mx:Script>
  <![CDATA[
   private function changeCSS():void{
    StyleManager.loadStyleDeclarations("myCSS.swf");
    
   }
   private function undoStyle():void{
    StyleManager.unloadStyleDeclarations("myCSS.swf");
   }
  ]]>
 </mx:Script>
 <mx:Button label="change css" click="changeCSS()"/>
 <mx:Button label="revert css" click="undoStyle()"/>
 <mx:Label text="hi there"/>
 <mx:Label text="hi there" styleName="text1"/>
 <mx:Label text="hi there" styleName="text2"/>
</mx:Application>
 

myCSS.css

Application{
 color:#ff0000;
 font-size:40;
}
.text1{
 color:#00ff00;

Compile the css into a swf, and make sure it is in the same directory as the TestLoadStyles.swf. As you run the application, you can see the changes as the style sheet is loaded or unloaded.  One thing to notice, is that even when the styles are loaded, and styles initially defined, which are not overridden in the loaded style sheet still remain, therefore, the styles of .text2 (yellow text), remain yellow, even after the new style sheet is loaded, since the .text2 style does not appear in the load style sheet, while the style .text1 which is defined as red text in the initial application, is changed to green, as the same style name is defined in both, so when the new style sheet is loaded, the .text1 label changes its color from green to red, and when its unloaded, it reverts to green.

This offers great opportunities not only for greater separation of styles from the application, but also for the concepts of writing an application once and rebranding the same deployed application.

There are no comments.

Leave a Reply