Oleksiy
Oleksiy

Reputation: 39810

How to center the text inside a Button regardless of drawableLeft?

I want the text centered in the Button. But whenever I add android:drawableLeft xml attribute to the Button, it offsets the text. How can I fix that?

share button

The only way I managed to fix it is by setting a negative number in android:drawablePadding:

enter image description here

But I'm looking for a cleaner solution to achieve it.

Upvotes: 2

Views: 1302

Answers (5)

Matt Robertson
Matt Robertson

Reputation: 3165

Unfortunately there's no clean way to do this. One fairly straightforward way is to set a transparent ColorDrawable of equal size on the opposite side of the button.

val drawableSize = button.height // adjust this as desired of course

realDrawable.setBounds(0, 0, drawableSize, drawableSize)

val emptyDrawable = ColorDrawable(Color.TRANSPARENT).apply {
    setBounds(0, 0, drawableSize, drawableSize)
}

button.setCompoundDrawables(realDrawable, null, emptyDrawable, null)

Upvotes: 0

Julio fils
Julio fils

Reputation: 75

android:gravity="center_vertical"

Upvotes: 0

Oleksiy
Oleksiy

Reputation: 39810

So I ended up going with the lesser of the evils, and that's placing the drawable and the text inside RelativeLayout:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/Button.ButtonGray"
    android:id="@+id/share_button">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/btn_share"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:layout_centerInParent="true"
        style="@style/TextNormalWeight"
        android:text="@string/post_share"/>

</RelativeLayout>

The RelativeLayout then receives click events and acts and looks like a button.

Upvotes: 1

Budius
Budius

Reputation: 39836

unfortunately that is the Button behaviour and I agree with you that negative padding is kind of a dirty hack, so I'll propose two other hacks that to me sounds a little less dirty because they rely on expected behaviour (negative padding although works it's not by design):

  • set android:paddingRight on the button to the size of the drawables
  • create a drawable with the same size of the left drawable but with all transparent pixels and put as right drawable.

Upvotes: 1

cobes
cobes

Reputation: 93

It works with:

android:gravity="center"

Upvotes: -1

Related Questions