1
votes

I am working on an application where I need to basically have 2 separate screens and I need to be able to switch between them. I am a total noob to Flex & Flash and I have not found anything on how to do this in my 2 days of Googling. It really shouldn't be this hard to do! :)

Here is what I have tried. I created a Flex Project and added 2 MXML Component files called Test1 & Test2 and each simply have a button in them which have a label of Button1 & Button2 so I can see if the correct component is showing. Below is the button code in the Test1 MXML Component file:

<s:Button id="btn1" label="Button1" click="currentState = 'State2'">

In the MXML Application file I have 2 States called State1 & State2. I have added the following to this file as well:

<local:Test1 includeIn="State1" x="0" y="0"></local:Test1>
<local:Test2 includeIn="State2" x="0" y="200"></local:Test2>

I have also added the states to all 3 files:

<s:states> 
    <s:State name="State1"/>
    <s:State name="State2"/>
</s:states>

When I run the application, I see Test1 as I would expect since State1 is the first state listed. When I click the button in Test1 (labeled Button1), I would expect it to now show the Test2 MXML component (since I am changing the currentState to 'State2', but it does not. Test1 is still displayed with Button1 showing.

Can someone shed some light as to what I am doing wrong? Or propose a better (or proper) way of doing this?

Thanks in advance!

1

1 Answers

2
votes

Sounds like the states in your Application are not connected to the states in your components. Just giving them the same name doesn't connect them in any way. Anyway, if you're just trying to hide/switch components in your main Application you really only need the states in there.

One option would be to just access the Application's currentState property directly from within the components:

<s:Button id="btn1" label="Button1" click="FlexGlobals.topLevelApplication.currentState = 'State2'"/>

That works, but it's not recommended because it strongly couples the component with the parent Application and in a large project will lead to a mess if you have to refactor (or work with other people).

Another option, is to have each component dispatch an event to let the parent know it should change:

<fx:Metadata>
  [Event(name="changeParentState", type="flash.events.Event")]
</fx:Metadata>
<s:Button id="btn1" label="Button1" click="dispatchEvent(new Event('changeParentState'));"/>

Then, the parent would decide which state it should switch to:

<local:Test1 includeIn="State1" changeParentState="currentState='State2'" />
<local:Test2 includeIn="State2" changeParentState="currentState='State1'" />

This way is more generic and just better OOP. However, if you'd want your components to be able to trigger more than just a single state, you might have to do something more complex. This should give you a sense of where to go at least.