Skip to content

Floating Action Buttons

Nathan Esquenazi edited this page Oct 20, 2015 · 111 revisions

Overview

Floating action buttons (or FAB) are: “A special case of promoted actions. They are distinguished by a circled icon floating above the UI and have special motion behaviors, related to morphing, launching, and its transferring anchor point.”

For example, if we are using an email app and we are listing the inbox folder, the promoted action might be composing a new message.

FAB1  FAB2

The floating action button represents the primary action within a particular screen. More info and use cases of the FAB button from Google’s official design specs can be found here.

Usage

Google made available during Google I/O 2015 a support library to create floating action buttons library. In the past, third-party libraries such as makovkastar/FloatingActionButton and futuresimple/android-floating-action-button had to be used.

Design Support Library

Make sure to follow the Design Support Library setup instructions first.

You should now be able to add the android.support.design.widget.FloatingActionButton view to the layout. The src attribute references the icon that should be used for the floating action.

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

In addition, assuming xmlns:app="http://schemas.android.com/apk/res-auto is declared as namespace the top of your layout, you can also define a custom attribute fabSize that can reference whether the button should be normal or mini.

To place the floating action button, you will use CoordinatorLayout. A CoordinatorLayout helps facilitate interactions between views contained within it, which will be useful later to describe how to animate the button depending on scroll changes. For now we can take advantage of a feature in CoordinatorLayout that allows us to hover one element over another. We simply need to have the ListView and FloatingActionButton contained within the CoordinatorLayout and use the layout_anchor and layout_anchorGravity attributes.

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/main_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

          <ListView
              android:id="@+id/lvToDoList"
              android:layout_width="match_parent"
              android:layout_height="match_parent"></ListView>

          <android.support.design.widget.FloatingActionButton
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_gravity="bottom|right"
              android:layout_margin="16dp"
              android:src="@drawable/ic_done"
              app:layout_anchor="@id/lvToDoList"
              app:layout_anchorGravity="bottom|right|end" />

</android.support.design.widget.CoordinatorLayout>

The button should be placed in the bottom right corner of the screen. The recommended margin for the bottom is 16dp for phones and 24dp for tablets. In the example above, 16dp was used.

The actual drawable size should be 24dp according to the Google design specs.

Animating the Floating Action Button

When a user scrolls down a page, the floating action button should disappear. Once the page scrolls to the top, it should reappear.

To animate this part, you will need to take advantage of CoordinatorLayout, which helps choreograph animations between views defined within this layout.

Converting from ListView to RecyclerView

Currently, you need to convert your ListViews to use RecyclerView. RecyclerView is the successor to ListView as described in this section. There is no support built-in for CoordinatorLayout to work with ListView according to this Google post. You can review this guide to help make the transition.

<android.support.v7.widget.RecyclerView
         android:id="@+id/lvToDoList"
         android:layout_width="match_parent"
         android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>

You also must upgrade to the v22 version of RecyclerView. Previous v21 versions will not work with CoordinatorLayout. Make sure to bump your build.gradle file:

    compile 'com.android.support:recyclerview-v7:22.2.1'

Using CoordinatorLayout

Next, you must implement a CoordinatorLayout Behavior for the Floating Action Button. This class will be used to define how the button should respond to other views contained within the same CoordinatorLayout.

Create a file called ScrollAwareFABBehavior.java that extends from FloatingActionButton.Behavior. Currently, the default behavior is used for the Floating Action Button to make room for the Snackbar as shown in this video. We want to extend this behavior to signal that we wish to handle scroll events in the vertical direction:

public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {

    @Override
    public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
            FloatingActionButton child, View directTargetChild, View target, int nestedScrollAxes) {
        return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || 
            super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target,
            nestedScrollAxes);
    }

}

Because scrolling will be handled by this class, a separate method [onNestedScroll()](https://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.Behavior.html#onNestedScroll(android.support.design.widget.CoordinatorLayout, V, android.view.View, int, int, int, int)) will be called. We can check the Y position and determine whether to animate in or out the button.

Thanks to a recent upgrade to the support v4 library, there is also a show() and hide() method available that performs the fade-in and fade-out animations for Floating Action Buttons. Previously, much of the animation code had to be reimplemented.

public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
    // ...

    @Override
    public void onNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child,
            View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed,
                dyUnconsumed);

        if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
            child.hide();
        } else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
            child.show();
        }
    }

    // ...
}

The final step is to associate this CoordinatorLayout Behavior to the Floating Action Button. We can define it within the XML declaration as a custom attribute app:layout_behavior:

<android.support.design.widget.FloatingActionButton    
    app:layout_behavior="com.codepath.floatingactionbuttontest.ScrollAwareFABBehavior" />

Because we are defining this behavior statically within the XML, we must also implement a constructor to enable layout inflation to work correctly.

public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
    // ...

    public ScrollAwareFABBehavior(Context context, AttributeSet attrs) {
        super();
    }

   // ...
}

If you forget to implement this last step, you will see Could not inflate Behavior subclass error messages. See this example code for the full set of changes.

Note: Normally when implementing CoordinatorLayout behaviors, we need to implement [layoutDependsOn()](https://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.Behavior.html#layoutDependsOn(android.support.design.widget.CoordinatorLayout, V, android.view.View)) and [onDependentViewChanged()](https://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.Behavior.html#onDependentViewChanged(android.support.design.widget.CoordinatorLayout, V, android.view.View)), which are used to track changes in other views contained within the CoordinatorLayout. Since we only need to monitor scroll changes, we use the existing behavior defined for the Floating Action Button, which is currently implemented to track changes for Snackbars and AppBarLayout as discussed in this blog post.

Embedding FloatingActionButton in Header

A common effect is embedding the FAB near the header like this:

This can be achieved by use CoordinatorLayout as the root view. We need to specify layout_anchor for the FAB to the top view and layout_anchorGravity to to bottom|right|end like this:

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

        <LinearLayout
            android:id="@+id/viewA"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.6"
            android:background="@android:color/holo_purple"
            android:orientation="horizontal"/>

        <LinearLayout
            android:id="@+id/viewB"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.4"
            android:background="@android:color/holo_orange_light"
            android:orientation="horizontal"/>

    </LinearLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:clickable="true"
        android:src="@drawable/ic_done"
        app:layout_anchor="@id/viewA"
        app:layout_anchorGravity="bottom|right|end"/>

</android.support.design.widget.CoordinatorLayout>

With FloatingActionButton (Third-Party)

Using makovkastar/FloatingActionButton library makes floating buttons quite simple to setup. See the library readme and the sample code for reference.

First, add as a dependency to your app/build.gradle:

dependencies {
    compile 'com.melnykov:floatingactionbutton:1.2.0'
}

Next, let's add the com.melnykov.fab.FloatingActionButton to our layout XML. Note the addition of the xmlns:fab to the attributes of the root layout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:fab="http://schemas.android.com/apk/res-auto"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <ListView
            android:id="@android:id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    <com.melnykov.fab.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|right"
            android:layout_margin="16dp"
            android:src="@drawable/ic_action_content_new"
            fab:fab_type="normal"
            fab:fab_shadow="true"
            fab:fab_colorNormal="@color/primary"
            fab:fab_colorPressed="@color/primary_pressed"
            fab:fab_colorRipple="@color/ripple" />
</FrameLayout>

Attaching to Lists

Next, we can optionally associate the FAB with a ListView, ScrollView or RecyclerView so the button will hide as the list is scrolled down and revealed as the list is scrolled up:

ListView listView = (ListView) findViewById(android.R.id.list);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.attachToListView(listView); // or attachToRecyclerView

We can attach to a RecyclerView with fab.attachToRecyclerView(recyclerView) or a ScrollView with fab.attachToScrollView(scrollView)

One limitation in using this third-party library is that implementing endless scrolling conflicts with this behavior because both attempt to listen for scroll events. The floating action button that comes with support design library is the recommended approach now.

Adjust Button Type

Floating action buttons come in two sizes: the default, which should be used in most cases, and the mini, which should only be used to create visual continuity with other elements on the screen.

Mini

We can adjust the FAB button type to "normal" or "mini":

<com.melnykov.fab.FloatingActionButton
    ...
    fab:fab_type="mini" />

Show or Hiding FAB

Show/hide the button explicitly:

// SHOW OR HIDE with animation
fab.show();
fab.hide();
// OR without animations
fab.show(false);
fab.hide(false);

Listening to Scroll Events

We can listen to scroll events on the attached list in order to manage the state of our FAB with:

FloatingActionButton fab = (FloatingActionButton) root.findViewById(R.id.fab);
fab.attachToListView(list, new ScrollDirectionListener() {
    @Override
    public void onScrollDown() {
        Log.d("ListViewFragment", "onScrollDown()");
    }

    @Override
    public void onScrollUp() {
        Log.d("ListViewFragment", "onScrollUp()");
    }
}, new AbsListView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        Log.d("ListViewFragment", "onScrollStateChanged()");
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, 
        int totalItemCount) {
        Log.d("ListViewFragment", "onScroll()");
    }
});

Manual Implementations

Instead of using a library we can also develop the floating action buttons manually. For manual implementations of the floating action button, see this big nerd ranch guide and the survivingwithandroid walkthrough.

References

Finding these guides helpful?

We need help from the broader community to improve these guides, add new topics and keep the topics up-to-date. See our contribution guidelines here and our topic issues list for great ways to help out.

Check these same guides through our standalone viewer for a better browsing experience and an improved search. Follow us on twitter @codepath for access to more useful Android development resources.

Clone this wiki locally