64. Using XML layouts in HaxeUI

2014-11-06

HaxeUI XML

In the previous tutorial I explained how to install HaxeUI and display its components programmatically.

Adding UI elements using code allows for dynamic layout manipulation, but is not always convenient. It is much easier to store layouts separately from code in XML files, and HaxeUI has the ability to do so.

Before we delve into layout creation, I should mention UI themes. HaxeUI has several built-in themes that you can use to change the appearance of all the controls in your application.

Changing a theme does not only alter the styling of a component, but may also affect its behavior. For example, GradientTheme will always display a scrollbar in a scrollable container, while DefaultTheme will only display it when the container is being scrolled. This makes some themes more suitable to be used in mobile applications than others.

To set a theme, change the Toolkit's theme property before calling the init() method:

Toolkit.theme = new GradientTheme();

Toolkit.init();

You can find the list of available built-in themes here.

Let's now create a simple layout in an XML file. You can use this builder to quickly see the results of your layout.

I created a simple scrollview container with a few controls (dividers, buttons and text fields) lined up vertically:

<?xml version="1.0" encoding="utf-8" ?>

<scrollview x="20" y="20" width="150" height="150">

    <vbox width="100%">

		<divider text="Divider" />

		<button text="Button" width="100%" />

		<text text="Text field" width="100%" />

		<button text="Button" width="100%" />

		<text text="Text field" width="100%" />

		<divider text="Divider" />

		<button text="Button" width="100%" />

		<text text="Text field" width="100%" />

		<button text="Button" width="100%" />

		<text text="Text field" width="100%" />

	</vbox>

</scrollview>

Save this as mainLayout.xml and put it in the assets/layouts/ directory of your project.

This asset path has to be declared in the applications.xml file:

<assets path="assets/layouts" rename="layouts" />

Back in Main.hx, you can load the layout from the resource and display it using the processXmlResource() method.

Toolkit.openFullscreen(function(root:Root) {

	var view:IDisplayObject = Toolkit.processXmlResource("layouts/mainLayout.xml");

	root.addChild(view);

});

You can see that the layout described in the resource is converted into an actual component (which implements IDisplayObject), which can then be added to the root just like any other component.