HTML中有一个非常好的特性就是可以动态切换页面链接的CSS样式表,而FLEX并不具备动态导入CSS的特性,因为FLEX的所有的UI外观都是在后台SERVER生成在发布到前台的(当然,通过AS可以实时更改UI外观setStyle,这是单个更改的方式,并不是实时的CSS文件切换),一直觉得挺不爽的,今天在mannu看到一个使用_global.styles来实现动态切换CSS文件的非常巧妙的方式:

首先,因为FLEX是将CSS编译进SWF文件的,所有我们将我们需要切换的CSS编译成SWF文件;

green.css

Label{
   color:#00FF00;
   fontSize:20px;
}

green.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml">

   <mx:Style source="green.css"></mx:Style>

</mx:Application>

类似的还有red.css/red.mxml,blue.css/blue.mxml。
然后,我们要切换到相应的CSS就直接LOAD相应的SWF文件;
最后,将_global.styles设置为所导入的SWF文件的_global.styles 。
这里有一个工具封装好的工具类:

RuntimeStyle.as

import mx.controls.Loader;
import mx.core.MXMLObject;
import mx.utils.Delegate;

class RuntimeStyle implements MXMLObject
{

 private var _document:Object;
 private var loader:Loader;

 public function initialized(document:Object, id:String):Void
 {
   _document = document;
 }

 private var _source:String;

 public function get source():String
 {
   return _source;
 }

 public function set source(value:String):Void
 {
   if (_source != value)
   {
     _source = value;

    if (loader == undefined)
     {
       loader = Loader(_document.createClassObject(Loader,
             "runtimeStyleLoader", 21983));
       loader.width = loader.height = 0;
       loader.addEventListener("complete",
           Delegate.create(this, loader_complete));
     }

    loader.source = _source + ".swf";
   }
 }

 private function loader_complete(event:Object):Void
 {
   _global.styles = Loader(event.target).content._global.styles;
   _document.styleName = _document.styleName == "!" ? "@" : "!";
 }

}

测试代码:

cssChg.mxml

<local:RuntimeStyle xmlns:local="*"

 source="{stylesWrappers.selectedItem.source}" />

<mx:Model id="alternateStyles"

 source="alternateStyles.xml" />

<mx:ComboBox id="stylesWrappers"
 dataProvider="{alternateStyles.stylesheet}"
 labelField="name" selectedIndex="-1" />

alternateStyles.xml

<?xml version="1.0" encoding="UTF-8"?>
<styles>

   <stylesheet>
       <name>red</name>
       <source>red.mxml</source>
   </stylesheet>
   <stylesheet>
       <name>green</name>
       <source>green.mxml</source>
   </stylesheet>
   <stylesheet>
       <name>blue</name>
       <source>blue.mxml</source>
   </stylesheet>

</styles>

演示地址