Flex addChild()方法注意事項(xiàng)
更新時(shí)間:2009年08月03日 23:36:22 作者:
在Flex Application里,是不能直接用addChild添加Sprite,MovieClip等來(lái)自flash.display包里的類的。
譬如以下代碼就會(huì)報(bào)錯(cuò):
private function init():void { var sp:Sprite = new Sprite(); addChild(sp);}
TypeError: Error #1034: 強(qiáng)制轉(zhuǎn)換類型失敗:無(wú)法將 flash.display::Sprite@156b7b1 轉(zhuǎn)換為 mx.core.IUIComponent。
這是因?yàn)锳pplication的addChild方法并非完全繼承自DisplayObjectContainer,
Application→LayoutContainer→Container →UIComponent→FlexSprite→Sprite
→DisplayObjectContainer
而是在Container那里被重寫了:
public override function addChild(child:DisplayObject):DisplayObject雖然參數(shù)child的類型是DisplayObject,但是它必須實(shí)現(xiàn)IUIComponent接口(所有Flex組件都實(shí)現(xiàn)了這一接口),才能添加。
如果要在Application里添加Sprite,可以先把它裝進(jìn)一個(gè)UIComponent,然后再添加這個(gè)UIComponent:
官方的說(shuō)法:
* <p><b>Note: </b>While the <code>child</code> argument to the method
* is specified as of type DisplayObject, the argument must implement
* the IUIComponent interface to be added as a child of a container.
* All Flex components implement this interface.</p>
例子:
import mx.core.UIComponent;private function init():void {
var sp:Sprite = new Sprite();
var uc:UIComponent = new UIComponent();
uc.addChild(sp); addChild(uc);
}
private function init():void { var sp:Sprite = new Sprite(); addChild(sp);}
復(fù)制代碼 代碼如下:
TypeError: Error #1034: 強(qiáng)制轉(zhuǎn)換類型失敗:無(wú)法將 flash.display::Sprite@156b7b1 轉(zhuǎn)換為 mx.core.IUIComponent。
這是因?yàn)锳pplication的addChild方法并非完全繼承自DisplayObjectContainer,
Application→LayoutContainer→Container →UIComponent→FlexSprite→Sprite
→DisplayObjectContainer
而是在Container那里被重寫了:
復(fù)制代碼 代碼如下:
public override function addChild(child:DisplayObject):DisplayObject
如果要在Application里添加Sprite,可以先把它裝進(jìn)一個(gè)UIComponent,然后再添加這個(gè)UIComponent:
官方的說(shuō)法:
* <p><b>Note: </b>While the <code>child</code> argument to the method
* is specified as of type DisplayObject, the argument must implement
* the IUIComponent interface to be added as a child of a container.
* All Flex components implement this interface.</p>
例子:
復(fù)制代碼 代碼如下:
import mx.core.UIComponent;private function init():void {
var sp:Sprite = new Sprite();
var uc:UIComponent = new UIComponent();
uc.addChild(sp); addChild(uc);
}
相關(guān)文章
Flex 處理服務(wù)器端傳來(lái)的數(shù)據(jù)
對(duì)于Java端返回的各種Java類型的對(duì)象,F(xiàn)lex中能否有相應(yīng)的數(shù)據(jù)類型來(lái)映射。這是Flex與服務(wù)器通信使用remoteObject的關(guān)鍵。2009-08-08
如何定義一個(gè)getter和seter設(shè)置的屬性可以被綁定
Define private variable for maxFontSize.2009-05-05
Flex 動(dòng)態(tài)綁定BindingUtils.bindProperty
Flex 動(dòng)態(tài)綁定BindingUtils.bindProperty實(shí)現(xiàn)代碼。2009-06-06

