Centering a Field in a HorizontalFieldManager

/* This is my horizontal field manager that will contain a centered field.
 * AbstractHorizontalFieldManager is a Metova specific manager that handles
 * initialization and loading automatically.
 */
private class MyHorizontalFieldManager extends AbstractHorizontalFieldManager {

    private Field field;

    public MyHorizontalFieldManager() {

        /* if we do not use all width, then the horizontal field manager
         * will shrink to the size of it's contents
         */
        super( USE_ALL_WIDTH | NO_HORIZONTAL_SCROLL );
    }

    protected void initializeFields() {

        // initialize the field
        setField( new AbstractButton( "My Button", new Action() {

            public void run() {

                log.debug( "My button was pressed." );
            }
        } ) );
    }

    protected void addFields() {

        // add the field to the manager
        add( getField() );
    }

    protected void sublayout( int width, int height ) {

        super.sublayout( width, height );

        // get the updated dimensions
        width = getWidth();
        height = getHeight();

        // make sure that the field is not null, and that it has been added.
        Field field = getField();
        if ( field != null && equals( field.getManager() ) ) {

            // get the centering coordinates
            int x = (int) ( ( width - field.getWidth() ) * 0.50 );

            // set the position for the field
            setPositionChild( field, x, 0 );
        }
    }

    private Field getField() {

        return field;
    }

    private void setField( Field field ) {

        this.field = field;
    }
}
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.
  1. Jul 28, 2009

    Mark McEver says:

    I think the official BB way to do this is to give the field the Field.FIELD_HCEN...

    I think the official BB way to do this is to give the field the Field.FIELD_HCENTER style, add the field to a VFM, then add that VFM to the HFM (see Field Alignment Using RIM's Alignment Styles). Why aren't we doing it this way?

    1. Jul 20, 2009

      Martin Reed says:

      With the alignment styles you have three choices: left, center, right. If you wa...

      With the alignment styles you have three choices: left, center, right. If you want more then you end up nesting Managers which will cause performance issues. With this method you have total control of the position.

© 2011 Metova, Inc.