FloatingActionButton Android Using Support Library Example

Google has introduced a support library through which Android FloatingActionButton can be added from 2.1 version onward.

Android Floating Action Button

 

Add the support design library as dependency in gradle file.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:design:22.2.0'
}

FloatingActionButton is extended from imageview & the behavior is similar to normal button. For eg,

   <android.support.design.widget.FloatingActionButton
        android:id="@+id/add_fab_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/abc_ic_ab_back_mtrl_am_alpha"
        app:elevation="4dp"
        app:borderWidth="0dp"/>

The default color of the floating button is taken from colorAccent propertie of the theme.

If you add 10 floating action button, then all will have default background as of colorAccent, you can override this propertie like, see the image below after updating gray color.

 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorAccent">@color/material_blue_grey_800</item>
  </style>

Colorful Floating buttons

To Change color for single button, simply update app:backgroundTint, for size of the button use app:fabSize

for eg: Red color mini button looks like below.

Floating Mini button

   <android.support.design.widget.FloatingActionButton
        android:id="@+id/close_fab_button"
        android:layout_below="@+id/add_fab_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/abc_ic_clear_mtrl_alpha"
        app:fabSize="mini"
        app:backgroundTint="#FF0000"
        app:elevation="4dp"
        app:borderWidth="0dp"/>

For Click event refer below code,

FabButton = (FloatingActionButton)findViewById(R.id.add_fab_button);
        
        FabButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
            }
        });

Use setImageDrawable to set the image dynamically to FAB.