Monday, November 21, 2016

Bottom Placement of Floating Action Button (FAB)

I recently wrote a new app and converted 2 existing apps to Material Design. Once of the things I had trouble figuring out was how to get the Floating Action Button (FAB) to be located at the lower right. It was simple once I found the solution.

Using a CoordinatorLayout for the Activity, the FAB should be the last item in the layout and have a layout_gravity of "bottom|right"
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:id="@+id/note_root_layout"
    tools:context="org.openstaxcollege.android.activity.NoteEditorActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay"/>

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

    <include layout="@layout/content_noteeditor"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_action_accept"
        android:layout_gravity="bottom|right"/>

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

A working example is in the OpenStax Android app. Look at the NoteEditorActivity.