Francesco Galgani
Francesco Galgani

Reputation: 6249

Vertical alignment of text and icon

Today I spent two hours trying to align vertically the text of a toogle button at the bottom of the button icon.

The button icon height is a three or four times longer than the text height: the text must be vertically aligned at the bottom of the icon.

The method setVerticalAlignment(int valign) works as expect if the parameter is Component.TOP or Component.CENTER, but Component.BOTTOM acts exactly as Component.CENTER.

I tried a lot of workarounds, without success. It’s odd that a so easy task is hard to do: am I missing something? Thank you.

I don’t know if it’s relevant, however I’m also using setTextPosition(Component.RIGHT).

Upvotes: 1

Views: 152

Answers (1)

Shai Almog
Shai Almog

Reputation: 52760

Edited answer...

That code is a bit difficult to work with and has so many nuances and misbehavior's. I usually end up just splitting the text and icon to separate labels and using something like a flow layout:

Form hi = new Form("Big and Small", BoxLayout.y());

CheckBox toggle = CheckBox.createToggle("My Text");
toggle.setUIID("Label");
Label bigIcon = new Label("");
FontImage.setMaterialIcon(bigIcon, FontImage.MATERIAL_INFO, 10);

Container lead = FlowLayout.encloseBottomInRow(toggle, bigIcon);
lead.setUIID("ToggleButton");
lead.setLeadComponent(toggle);
hi.add(lead);

hi.show();

Note that at this time this code requires a change that was added yesterday to the code (the ByRow method). Initially I thought this was a bug in FlowLayout but it seems it was just two different ways of calculating vertical alignment for the container.

enter image description here

To get a sense of why aligning and placing labels is so hard check out this code responsible for that: https://github.com/codenameone/CodenameOne/blob/fd2acfc10eb22f4b7a3089aeac4e967280f92b4e/CodenameOne/src/com/codename1/ui/plaf/DefaultLookAndFeel.java#L1314-L1623

This is just the generic code. There are copies of it in native iOS and Android code (for performance).

Upvotes: 1

Related Questions