Search code examples
androidfloating-action-button

How to make Floating Action Button background Gradient?


The code for FAB:

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right|end"
        android:layout_margin="16dp"
        android:src="@drawable/add_chat"
        android:tint="@android:color/white" />
</android.support.design.widget.CoordinatorLayout>

The code for gradient background:

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="oval">
<gradient
    android:angle="90"
    android:endColor="#e4849f"
    android:startColor="#d96e30" />
</shape>

android:backgroundTint="" or app:backgroundTint="" both uses color resources only.Can anyone suggest how to do this? Thanks !!


Solution

  • Step 1. Create a new drawable.xml and add this code to it

     <?xml version="1.0" encoding="utf-8"?>
        <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
    
            <item>
                <shape xmlns:android="http://schemas.android.com/apk/res/android"
                    android:shape="oval">
                    <gradient
                        android:type="linear"
                        android:angle="0"
                        android:startColor="#f6ee19"
                        android:endColor="#115ede" />
                </shape>
    
            </item>
            <item android:gravity="center"
                >
                <bitmap android:src="@drawable/your_icon"
                    android:gravity="fill_horizontal" />
    
            </item>
    
        </layer-list>
    

    Step 2.) Now in your dimens.xml add this line of code,

    <dimen name="design_fab_image_size" tools:override="true">56dp</dimen> 
    

    Step 3.) Finally set this drawable.xml in FAB using *android:src="@drawable/drawable.xml"*

    P.S. - Make sure your_icon is a PNG, JPEG.