使用ActionScript 3时,在当前的Container中需要加载外部的SWF文件,并给其中的button等组件添加监听事件。通常在ActionScript中加载SWF文件有有两种方式:一是通过Embed将外部SWF文件作为新类注册到当前类;二是通过Loader将SWF文件加载到当前Stage,通过该显示对象的root调用其中的组件。本文将介绍第二种使用方式。
在本文中,当前Stage的类为ExampleWrapper.as,需要加载的SWF文件名为custom.swf,与编译后生成的ExampleWrapper.swf放在同一文件夹下。
步骤为:
- 新创建一个Loader对象,加载custom.swf文件;
- 给loader添加监听事件,加载完成后访问SWF文件的组件;
- 给需要的组件添加事件。
代码如下:
public function loadSwf():void { var ldr:Loader = new Loader(); ldr.load(new URLRequest("custom.swf")); ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, initButtons); addChild(ldr); } private function initButtons(event:Event):void { exitBtn = event.target.content.root.exitBtn; exitBtn.stop(); exitBtn.addEventListener(MouseEvent.CLICK,function():void{Object(customWrapper).closeGame();ExternalInterface.call("closeWin");}); helpBtn = event.target.content.root.helpBtn; helpBtn.stop(); helpBtn.addEventListener(MouseEvent.CLICK,function():void{Object(customWraper).requestHelpPage();}); ... }
在initButtons方法中,通过root.访问到加载的显示对象中的exitBtn与helpBtn,并给其添加了监听事件。