Tutorial

Android Floating Action Button Example Tutorial

Published on August 4, 2022
author

Anupam Chugh

Android Floating Action Button Example Tutorial

Today we will learn about Android Floating Action Button. We’ll discuss the FloatingActionButton, that’s a new component included in the Material Design Guidelines and SnackBar, which is a Material Design replacement of a Toast.

Android Floating Action Button

Android Floating Action Button is used to pay emphasis to the most important function on the screen. It’s a cool and stylish way to get user’s attention to it.

Android Floating Action Button Overview

To use Material Design widgets in our project we need to compile the following dependency in our build.gradle file as shown below.

compile 'com.android.support:design:23.1.1'

The FloatingActionButton widget is defined in the xml layout as follows:

<android.support.design.widget.FloatingActionButton
      android:id="@+id/fab"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@android:drawable/ic_dialog_email"
      android:layout_gravity="bottom|end"
      app:elevation="6dp"
      app:pressedTranslationZ="12dp"/>

Few observations made from the above xml layout defined are:

  1. FloatingActionButton extends the ImageView class. This is evident from the android:src attribute defined.
  2. In the above xml layout elevation attribute is used to cast a shadow over the button and pressedTranslationZ causes the shadow to grow when pressed.

A FloatingActionButton is placed within a 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. SnackBar is a more enhanced widget when compared to a Toast. A SnackBar is invoked as follows:

Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

We have discussed SnackBar at length in another tutorial. Important Note: If you’ve been following these Android Tutorials well, you must have noticed that with the new build tools update to 23.1.1 the project structure of a new empty project has changed and the above mentioned widgets are present by default in a new Android Studio Project. So instead of implementing the above mentioned widgets, let’s take a quick tour of the new project structure.

Android Floating Action Button Example Project Structure

android floating action button example project As you can see a new xml layout file named content_main.xml is added. It’s the same as the earlier activity_main.xml.

Android Floating Action Button Example

The new activity_main.xml is given below:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.journaldev.floatingactionbutton.MainActivity">

    <android.support.design.widget.AppBarLayout
        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_main" />

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

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

A toolbar is added by default as a replacement of an ActionBar. It’s added inside an AppBarLayout which is a direct child of CoordinatorLayout The AppBarLayout is used to achieve various scrolling behaviours such as collapse, flex space, and quick return. The MainActivity.java is defined as given below:

package com.journaldev.floatingactionbutton;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

A new attribute is added to the application tag inside the AndroidManifest.xml named android:supportsRtl="true". This enables right to left layouts in the application. Running this default application produces an output like below: android floating action button example Android FloatingActionButton As you can see, on clicking the floating action button, a SnackBar is displayed. This brings an end to this tutorial. You can create a new project in Android Studio and run it to see these features. Note: Make sure that you’re using the latest build tools. Reference: Android Reference Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Anupam Chugh

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.