好吧,这并不是真正的添加或删除孩子。真正的问题是关于你的发展观点。
首先,您正在构建一个菜单,所以让菜单就是这样,一个发送信号以通知单击了哪个按钮的对象。
之后,您需要某种形式的容器来在接收到菜单消息时显示相关屏幕。
这个容器可以包含三个屏幕,Branding,Web & Print。
您可以将所有此屏幕可见属性设置为 false。
当容器接收到菜单信息时,它将选中的屏幕可见属性设置为 true,将其他屏幕设置为 false。
这样,您不必不断添加或删除子项,尝试跟踪您的 DisplayList 结构。
对菜单使用事件调度。
无论如何,这是一个粗略的例子,它不完整,但应该给你一个想法......
public class Menu extends Sprite
{
//A basic button instance
private var button:Sprite = new Sprite();
//The dispatcher dispatches & listen to events
//it acts as a connector between your container
//and the menu
private var dispatcher:EventDispatcher;
//The menu will be created in the Container
//the dispatcher will be passed as a parameter
//this is the connection between the two classes
//Please note that there are other ways to achieve
//a similar result..
public function Menu (dispatcher:EventDispatcher)
{
//assign the dispatcher instantiated in the container
//to a variable in order to manipulate it in this class
this.dispatcher = dispatcher;
//takes care of creating the menu
createMenu();
}
private function clickHandler( event:MouseEvent):void
{
//each time a button is click an event is dispatched
//that contains the name of the clicked button
dispatcher.dispatchEvent
( new MenuEvent(event.currentTarget.name));
}
private function createMenu():void
{
//here you load the XML, create the buttons
// and add the event listeners
//this is just an example for the logic
//it's irrelevant since the button will
//be created from the XML
button.name = "Branding";
addChild( button );
button.addEventListener
( MouseEvent.CLICK , clickHandler );
}
}
public class Container extends Sprite
{
private var button:Sprite = new Sprite();
//Here we instantiate a dispatcher
private var dispatcher:EventDispatcher = new EventDispatcher;
private var menu:Menu;
//a basic screen instance that could contain
//all that has to do with Branding for instance
private var screen1:Sprite = new Sprite();
//etc...
public function Container ()
{
//The dispatcher is set to listen to the events
//dispatched in the Menu class
dispatcher.addEventListener( MenuEvent.MENU , eventListener );
screen1.visible = false;
//now the menu can be created
menu = new Menu( dispatcher);
addChild( menu );
}
private function eventListener( event:MenuEvent):void
{
//set all the screens visibility to false
//here...
//get the event name and react accordingly
//here you can implement a switch
switch(event.name)
{
case "Branding":
//show Branding screen
screen1.visible = true;
break;
//etc...
}
}
}
public class MenuEvent extends Event
{
public const MENU:String = "Menu Event";
public var name:String;
//Check custom events for the rest of the code...
//Do a Google search for custom events
//shouldn't be too difficult to find
}