user-interfaceblackberryblackberry-editfield

Blackberry - Custom size EditField


I am trying to put together a dialog that should look like this:

Fill in the below fields
_______________ likes ____________________

where the "_" lines are the EditFields.

I am sticking all the fields in a HorizontalFieldManager, which I add to the dialog. Unfortunately, the first EditField consumes all the space on the first line. I have tried to override the getPreferredWidth() method of the EditField by creating my own class extending BasicEditField, but have had no success.

Surely there must be a simple way to force a certain size for an edit field. What am I missing?


Solution

  • Just like DaveJohnston said:

    class LikesHFManager extends HorizontalFieldManager {
        EditField mEditFieldLeft;
        LabelField mLabelField;
        EditField mEditFieldRight;
        String STR_LIKES = "likes";
        int mLabelWidth = 0;
        int mEditWidth = 0;
        int mOffset = 4;
    
        public LikesHFManager() {
            mEditFieldLeft = new EditField();
            mLabelField = new LabelField(STR_LIKES);
            mEditFieldRight = new EditField();
    
            mLabelWidth = mLabelField.getFont().getAdvance(STR_LIKES);
            int screenWidth = Display.getWidth();
            mEditWidth = (screenWidth - mLabelWidth) >> 1;
            mEditWidth -= 2 * mOffset;
    
            // calculate max with of one character
            int chMaxWith = mEditFieldLeft.getFont().getAdvance("W");
            // calculate max count of characters in edit field
            int chMaxCnt = mEditWidth / chMaxWith;
    
            mEditFieldLeft.setMaxSize(chMaxCnt);
            mEditFieldRight.setMaxSize(chMaxCnt);
    
            add(mEditFieldLeft);
            add(mLabelField);
            add(mEditFieldRight);
        }
    
        protected void sublayout(int maxWidth, int maxHeight) {
    
            int x = 0;
            int y = 0;
    
            int editHeight = mEditFieldLeft.getPreferredHeight();
            int labelHeight = mLabelField.getPreferredHeight();
    
            setPositionChild(mEditFieldLeft, x, y);
            layoutChild(mEditFieldLeft, mEditWidth, editHeight);
            x += mEditWidth;
            x += mOffset;
    
            setPositionChild(mLabelField, x, y);
            layoutChild(mLabelField, mLabelWidth, labelHeight);
            x += mLabelWidth;
            x += mOffset;
    
            setPositionChild(mEditFieldRight, x, y);
            layoutChild(mEditFieldRight, mEditWidth, editHeight);
            x += mEditWidth;
    
            setExtent(x, Math.max(labelHeight, editHeight));
        }
    }