Search code examples
codenameone

Codename One container equal width and height


I have an Android project that uses several containers inside a Grid Layout.

The containers' height and width are different and I am looking for a way to make them square.

enter image description here

I have tried it the following way:

int w = container.getWidth();
container.setHeight (w);

This does not not work, because:

a) container.setHeight(i) does not change the height of the container, and b) container.getWidth() returns 0.

What would be the best approach to obtain square containers?

EDIT

Here is a updated screenshot: left is before, right is after using the code sample.

enter image description here


Solution

  • Size is set by the layout manager. The layout manager effectively invokes setWidth/Height/X/Y to determine the bounds of the components. So any change you make to any one of those methods will be overridden by the layout manager.

    To explicitly define the size override calcPreferredSize() and return a uniform size ideally one that is calculated and not hardcoded e.g.:

    Container myContainer = new Container(new GridLayout(1, 1)) {
    
        @Override
        protected Dimension calcPreferredSize() {
            Dimension d = super.calcPreferredSize();
            int size = Math.max(d.getWidth(), d.getHeight());
            d.setWidth(size);
            d.setHeight(size);
            return d;
        }
    };