1

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

rainer
  • 3,295
  • 5
  • 34
  • 50

1 Answers1

1

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;
    }
};
Diamond
  • 7,428
  • 22
  • 37
Shai Almog
  • 51,749
  • 5
  • 35
  • 65
  • Thanks for looking into this. I am getting an error when calling calcPreferredSize on super: the method calcPreferredSize() is undefined for the type Object – rainer Mar 26 '21 at 19:09
  • @rainer You don't have to call `super.calcPreferredSize`, you should be overriding the method. Use the correct number of rows/columns in your code, I used 1x1 for the sample. See the edited answer. – Diamond Mar 26 '21 at 23:55
  • This needs to be in the subclass of the component that you want to have equal size – Shai Almog Mar 27 '21 at 04:06
  • Hi guys, sorry for the delay in responding. I was quite busy over the last days. I have used the code sample above in my project and didn't notice any difference between before and after in my project. The container size continues the same. I have added a screenshot. Is there anything eles I could try? – rainer Mar 31 '21 at 12:33
  • I think @Diamond edited the answer in a correct way but it might be confusing... Notice that the calc method should be implemented on the components that represent the yellow and transparent squares and not on the grid that contains them. – Shai Almog Apr 01 '21 at 03:19
  • This actually solved the issue. The problem I am having with the container not resizing is the border layout in which the container is embedded. Many thanks for responding and the patience. – rainer Apr 04 '21 at 13:32