Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MaterialButton with icon doesn't center text

I'm trying to use a Material Button where I want an icon to the very left, and then some text in the center. But when I put in the icon on the left for instance, I can clearly see the text being pushed to the right. Is there any way to avoid this? I want the text to be centered, and would like to avoid doing a hacky solution for it..

<com.google.android.material.button.MaterialButton
        android:id="@+id/testButton"
        style="@style/RevertedColorDefaultButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="TEST"
        android:textAlignment="center"
        app:icon="@drawable/some_icon"
        app:iconGravity="start"´
        app:iconTint="@color/colorPrimary"
        app:layout_constraintBottom_toTopOf="@id/someOtherButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.94" />

For info, I tried the same thing with a regular button, same issue:

<androidx.appcompat.widget.AppCompatButton
        android:id="@+id/test2Button"
        style="@style/RevertedColorDefaultButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:drawableStart="@drawable/some_icon"
        android:drawableTint="@color/colorPrimary"
        android:text="TEST"
        app:layout_constraintBottom_toTopOf="@id/someOtherButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.94" />

Edit: Image added

enter image description here

like image 877
Mikkel Larsen Avatar asked Jun 21 '19 09:06

Mikkel Larsen


2 Answers

To anyone viewing this later I found a way to do this through adding the intrinsic width of the icon as a negative padding to the button

<button>.iconPadding = -(icon?.intrinsicWidth ?: 0)

This is because the text is pushed by exactly the intrinsicWidth of the icon

like image 105
Napster Avatar answered Sep 20 '22 21:09

Napster


You can use the iconGravity attribute to change the position of the icon:

        <com.google.android.material.button.MaterialButton
            style="@style/Widget.MaterialComponents.Button"
            app:icon="@drawable/ic_add_24px"
            app:iconGravity="textStart"
            android:text="BUTTON"
            />

enter image description here

You can also reduce the padding between the text and the icon with the iconPadding attribute:

        <com.google.android.material.button.MaterialButton
            app:iconGravity="textStart"
            app:iconPadding="0dp"
            ../>

enter image description here

like image 33
Gabriele Mariotti Avatar answered Sep 20 '22 21:09

Gabriele Mariotti