I got stuck in an odd issue with Android - I want to have a button that looks like this:
|-----------------------------------------------------------------------|
| [icon] <5px> [text text text] |
|-----------------------------------------------------------------------|
and the group ([icon] <5px> [text text text]) should be centred. Note that 5px is used just as a placeholder for any padding you want to have between the icon and the text
I found some answers here that were more or less graviting around either setting a background (which I don't want to do because I have another background) or using the android:drawableLeft property to set the icon.
However looks like the documentation of the setCompoundDrawablesWithIntrinsicBounds method is a bit misleading (see here). It states that the image is placed on the left/right/top/bottom side of the TEXT wich is not true. The icon is placed on the corresponding side of the BUTTON. For example:
Setting the android:drawableLeft property puts the icon on the most left position and gets me this (with gravity CENTER):
|-----------------------------------------------------------------------|
| [icon] [text text text] |
|-----------------------------------------------------------------------|
or this (with gravity LEFT):
|-----------------------------------------------------------------------|
| [icon] [text text text] |
|-----------------------------------------------------------------------|
Both are 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 don't find it to my liking for following reasons:
- it requires to know the button width. With auto-sized buttons it will not be known until the actual layout is done. Google recommend using a listener to learn the actual width after the rendering is done but this immensely complicates the code.
- I feel like I'm taking over the layout responsibility from the Android layout engine
Isn't there a more elegant solution?