The anchors feature is simple to use and is very effective with implementing flexible layouts.
By default the views position is relative to the top left corner.
There is nothing special about this corner and there is no real reason for all views to be position based on the distance from this specific corner.
By changing the horizontal or vertical anchors we can set the position relative to other sides of the screen or parent view.
So if want a button to always be close to the bottom of the screen then we will set the vertical anchor to BOTTOM and then set the distance. No matter what is the screen size the button will always be anchored to the bottom (anchor = distance to the relevant edge is constant).
The horizontal BOTH setting means that the distance from the view's left side to the screen (or parent) left edge is constant and that the distance from the view's right side to the screen (or parent) right edge is constant. This means that the width will change based on the device screen size.
BOTH is useful for large views that should fill the available space.
BOTH setting is similar to the designer script SetTopAndBottom or SetLeftAndRight methods.
There are many things that cannot be done with anchors. For example you cannot put three buttons side by side (with the same width) and fill the available space. This should be implemented with a simple designer script.
Note that the anchors effect ends right before the designer script starts.
The attached jar file is a B4J app that demonstrates the effect of anchors. It includes two forms. One with a simple layout and another with the same layout loaded multiple times. The second demonstrates the important fact that anchors are relative to the parent.
There is no code, other than the code that loads the layouts, or designer script in this example.
If Java (8.40+) is installed on your computer then you can double click on the jar to run it.
Run it and change the forms size to see the (trivial?) effect.
See post #5 for tips about using BOTH anchors.
Attachments
Last edited: