Search code examples
androidbuttontextviewdrawable

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.


Solution

  • 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.