I want to have an Android Button with icon+text centered inside it. I'm using the drawableLeft attribute to set the image, this works well if the button has a width of "wrap_content"
but I need to stretch to max width so I use width "fill_parent"
. This moves my icon straight to the left of the button and I want both icon and text centered inside the button.
I've try setting up the padding but this only allows to give a fixed value so it is not what I need. I need to have icon+text aligned in the center.
<Button
android:id="@+id/startTelemoteButton"
android:text="@string/start_telemote"
android:drawableLeft="@drawable/start"
android:paddingLeft="20dip"
android:paddingRight="20dip"
android:width="fill_parent"
android:heigh="wrap_content" />
Any suggestions on how I could achieve that?
android:drawableLeft is always keeping android:paddingLeft as a distance from the left border. When the button is not set to android:width="wrap_content", it will always hang to the left!
With Android 4.0 (API level 14) you can use android:drawableStart attribute to place a drawable at the start of the text. The only backward compatible solution I've come up with is using an ImageSpan to create a Text+Image Spannable:
Button button = (Button) findViewById(R.id.button);
Spannable buttonLabel = new SpannableString(" Button Text");
buttonLabel.setSpan(new ImageSpan(getApplicationContext(), R.drawable.icon,
ImageSpan.ALIGN_BOTTOM), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
button.setText(buttonLabel);
In my case I needed to also adjust the android:gravity attribute of the Button to make it look centered:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="32dp"
android:minWidth="150dp"
android:gravity="center_horizontal|top" />