Android: Floating Action Button

Credit: material.io

From Google Material Design docs:

A floating action button represents the primary action in an application. Shaped like a circled icon floating above the UI, it has an ink wash upon focus and lifts upon selection. When pressed, it may contain more related actions.

Adding resources

Add the latest appcompat and design support library to your project.

dependencies {
//replace X.X.X with the latest version
compile 'com.android.support:appcompat-v7:X.X.X'
compile 'com.android.support:design:X.X.X'
}

Make your activity extend AppCompatActivity.

public class FABActivity extends AppCompatActivity {
...
}

Add the button to the layout.

<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_favorite_white_24dp"
app:fabSize="normal"
app:rippleColor="@color/colorAccent" />

Now you should have your floating action button in your app. The attributes on the buttons are:

  • fabSize : Defines the size of the button. Available values are auto, normal and mini. You can see the size values on the Material Docs site.
  • rippleColor : Defines the color of the ripple effect applied when button is pressed.
Ripple color won’t be shown if there is no onClick listener on the button. So you can only see it’s effect after adding a listener to it.

Most probably you’ll want your button to be at bottom right of your page so you can put it in a relative layout and add layout_alignParentRight and layout_alignParentBottom to it.

Changing colors

For changing colors, create a custom style for the button in your styles.xml …

<style name="PrimaryActionButton" parent="Theme.AppCompat.Light">
<item name="colorAccent">@color/colorPrimary</item>
</style>

and add it’s reference to your button.

<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_favorite_white_24dp"
android:theme="@style/PrimaryActionButton"
app:fabSize="normal"
app:rippleColor="@color/colorAccent" />

Enjoy with your pretty floating action button!