Search code examples
androidstylesfloating-action-button

How to customise Floating Action Button to have different look and feel for enabled and disabled FAB state in Android?


There is no difference in appearance when FAB is disabled or enabled. How can I achieve a different look and feel for enabled and disabled FAB via xml?


Solution

  • I was able to have different look and feel for FAB. The steps I took are -

    1) Created a drawable custom_fab.xml at /res/drawable with following content:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/fab_disabled"
            android:state_enabled="false" />
        <item android:drawable="@drawable/fab_enabled"
            android:state_enabled="true" />
    </selector>
    

    This is to have different image for enabled and disabled state.

    2) Created a color selector custom_fab_color.xml at /res/color with following content:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:color="@color/colorFabDisabled" 
            android:state_enabled="false" />
        <item android:color="@color/colorFabEnabled" android:state_enabled="true" /> 
    </selector>
    

    This is to have different background color for enabled and disabled state of FAB.

    3) Added desired color for enabled and disabled state in res/values/colors.xml

    <resources>
        ...
        <color name="colorFabEnabled">#03DAC5</color>
        <color name="colorFabDisabled">#6DABF9</color>>
    </resources>
    

    4) Updated xml file where FAB is defined. Pointed the src and backgroundTint to the new drawable and color selector.

    <com.google.android.material.floatingactionbutton.FloatingActionButton
            ...
    
            android:backgroundTint="@color/custom_fab_color"
            android:src="@drawable/custom_fab" />