Tuesday, June 14, 2011

Containers and Layouts in Flex

Today we will learn about container types and layout objects in Flex.

There are multiple containers available in Flex, here are some of them:

  • Group - the most simple container in Flex, can contain children, but doesn't have any visual appearance on its own.
  • SkinnableContainer - same as Group, except that we can define this container's visual appearance on the screen.
  • BorderContainer - a type of SkinnableContainer that can be used to surround its children with a border.
  • Panel - a type of SkinnableContainer, surrounded by border and can have a header and a control bar.
  • Application - a type of SkinnableContainer that can be used as the root of this Flex application. It also has a control bar like the Panel.
  • NavigationContent - a type of SkinnableContainer used with a control called ViewStack, will explain in details later.

There are some other containers in Flex, but their roles are more specific than the ones listed above, and they will be also discussed in detail in later tutorials.

The content in containers can be placed in different patterns. For example, you could have buttons in your navigation bar stacked vertically, one under another, or you could have them placed in a horizontal line. The positioning of the content can be defined using layout objects.

There are 4 types of layout objects:

  • BasicLayout - the layout that is set by default. You manually set the x and y coordinates of each child.
  • HorizontalLayout- objects are arranged in a horizontal line.
  • VerticalLayout - objects are arranged in a vertical line.
  • TileLayout - children are arranged in rows and columns.

Let's see how to use the containers.

If you read my previous tutorials, you are already familiar with the BasicLayout in containers - we've placed a Label, a TextInput and a Button components in a Group container and set their coordinates manually. We never specified a layout, thus we used the default one, which is BasicLayout.

Create a new project or edit the existing one from the previous tutorials. Let's write some code for grouping buttons and set their layout.

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"

<s:Group x="20" y="20">
<s:HorizontalLayout />

<s:Button label="File" />
<s:Button label="Edit" />
<s:Button label="View" />
<s:Button label="About" />


If you test the code, the buttons will be arranged like this:

Let's try the VerticalLayout type of layout now:

<s:VerticalLayout />

The buttons will be stacked in a column:

Now, let's try the TileLayout. Let's specify the number of rows that we want to be there using the requestedRowCount attribute:

<s:TileLayout requestedRowCount="2" />

The results:

And this concludes today's tutorial.

Thanks for reading!

No comments:

Post a Comment