Mybeky's blog Addchild () February 15th, 2008 in flex Application
In the flex application, you cannot directly use addchild to add Sprite, movieclip, and other classes from the flash. Display package. For example, the following code reports an error:
- Private function Init (): void {var SP: SPRITE = new sprite (); addchild (SP );}
private function init():void { var sp:Sprite = new Sprite(); addChild(sp);}
Typeerror: Error #1034: forced conversion type failed: Flash. display: SPRITE @ 156b7b1 cannot be converted to MX. Core. iuicomponent.
This is because the addchild method of application is not completely inherited from displayobjectcontainer,
Application → layoutcontainer →Container→ Uicomponent → flexsprite → Sprite
→ Displayobjectcontainer
Instead, it is overwritten in the container:
- Public override function addchild (Child: displayobject): displayobject
public override function addChild(child:DisplayObject):DisplayObject
Although the type of the parameter child is displayobject, it must implement the iuicomponent interface (all flex components have implemented this interface) before it can be added.
If you want to add sprite to the application, you can first load it into a uicomponent, or use uimovieclip, and then add the uicomponent:
- Import MX. core. uicomponent; Private function Init (): void {var SP: SPRITE = new sprite (); var UC: uicomponent = new uicomponent (); UC. addchild (SP); addchild (UC );}
import mx.core.UIComponent;private function init():void { var sp:Sprite = new Sprite(); var uc:UIComponent = new UIComponent(); uc.addChild(sp); addChild(uc);}