BlackBerry UI – Creating a basic field manager

If you build apps using RIM’s BlackBerry user interface classes (and if you’re trying to build professional applications on BlackBerry, you should be using them) sooner or later you’ll have to start building your own field managers.

Creating managers is actually very easy. I’ll proceed by way of illustrative example – how to code a manager from scratch.


My previous post created a simple Hello World app – containing one screen with a single LabelField.

That label field appears at the top-left of the screen. What if we wanted to center it at the top of the screen?

We could try changing a couple of things. First, by reading the BlackBerry Javadocs, you might notice that the MainScreen (from which our screen is derived) automatically uses a VerticalFieldManager – maybe what we want to do is to embed our LabelField into a HorizontalFieldManager, set the style of our LabelField to FIELD_HCENTER and add that to the screen? We’ll make the HorizontalFieldManager use all width just to be on the safe side.

Try it:

view plaincopy to clipboardprint?
  1. LabelField lf = new LabelField(“Hello World!”, Field.FIELD_HCENTER);
  2. HorizontalFieldManager hfm = new HorizontalFieldManager(Manager.USE_ALL_WIDTH);
  3. hfm.add(labelField);
  4. add(hfm);

What gives? USE_ALL_WIDTH doesn’t seem to do what it should do.

Now, I can tell you that HorizontalFieldManager can be tweaked to make it center the field in the screen, but since we’re talking about managers, let’s instead fix this problem by creating our own.


Manager is an abstract class, with one abstract method – sublayout(int width, int height)

What sublayout is passed in are the width and height of its parent – the manager that contains it, which continues up to the top level screen. This is another thing about BlackBerry UIs – you’ll probably end up dealing with nested managers, so try to visualize which manager contains which.

A little exploratory coding tells us that when we add a manager directly to the screen, it is indeed passed the full screen width. So our task is pretty easy. We have to:

1. Get our centered field (for simplicity, we’ll assume we’re only going to ever add one field to this manager)
2. Get the width and height of the field to be centered
3. Figure out where to position the field to center it, based on the field’s width
4. Make our manager take up the entire available width

The code to do this is straightforward:

Leave a Reply

Your email address will not be published. Required fields are marked *