I am stuck in an unusual problem with Android - I want to have a button that looks like this:
|-----------------------------------------------------------------------| | [icon] <5px> [text text text] | |-----------------------------------------------------------------------|
and the group ([icon] <5px> [text text to text]) should be centered. Note that 5px is used as a placeholder for any add-on that you want between the icon and the text.
I found here a few answers that more or less gravitated towards setting the background (which I don't want to do because I have a different background) or using the android: drawableLeft property to set the icon.
However, the documentation for the setCompoundDrawablesWithIntrinsicBounds method seems a bit misleading (see here) . It indicates that the image is placed on the left / right / top / bottom side of the TEXT, which is incorrect. The icon is placed on the corresponding side of the BUTTON. For instance:
Setting the android: drawableLeft property puts the icon in the leftmost position and gets me (with gravitational CENTER):
|-----------------------------------------------------------------------| | [icon] [text text text] | |-----------------------------------------------------------------------|
or this (with LEFT gravity):
|-----------------------------------------------------------------------| | [icon] [text text text] | |-----------------------------------------------------------------------|
Both ugly as hell :(
I found a workaround that looks like this:
public static void applyTextOffset(Button button, int buttonWidth) { int textWidth = (int) button.getPaint().measureText(button.getText().toString()); int padding = (buttonWidth / 2) - ((textWidth / 2) + Constants.ICON_WIDTH + Constants.ICON_TO_TEXT_PADDING); button.setPadding(padding, 0, 0, 0); button.setCompoundDrawablePadding(-padding); }
And it works more or less, but I do not find it on my own for the following reasons:
- This requires knowing the width of the button. With buttons with automatic size, it will not be known until the actual layout is completed. Google recommends using a listener to find out the actual width after rendering, but this makes the code very complicated.
- It seems to me that I am taking responsibility for the layout from the Android layout engine.
Is there a more elegant solution?