androidxmlandroid-layoutuser-interfacefloating-action-button

FloatingActionButton srcCompat icon shifts off-center after resizing


When I change the android:layout_width and android:layout_height attributes of my FloatingActionButton in the XML layout, the srcCompat icon becomes decentered.

This is a very basic setup with a native drawable where I have only modified the width and height to make the button slightly larger and added a few constraints using the design tool. As you can see in the image below, the icon shifts towards the top-left corner. Interestingly, if I make the FloatingActionButton smaller than its original size, the icon shifts towards the bottom-right corner.

Here is the relevant XML code:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/floatingActionButton"
    android:layout_width="74dp"
    android:layout_height="74dp"
    android:clickable="true"
    app:iconGravity="end"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.759"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.802"
    app:srcCompat="@drawable/ic_launcher_foreground" />

The image:

actionButton with off-centered icon

I want the icon to appear completetly centered, as it does normally before resizing it.

I have tried many things such as changing the padding, the app:maxImageSize, app:iconGravity,app:borderWidth, etc. expecting them to help me control the placement of the icon over the actionButton layout. These properties had no effect on the icon's alignment when the button size was increased in the XML layout.


Solution

  • Use app:fabCustomSize.

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/ic_launcher_foreground"
        app:fabCustomSize="74dp" />
    

    https://github.com/material-components/material-components-android/blob/master/docs/components/FloatingActionButton.md#sizing-fabs