Last Updated:

FloatingActionButton in Android with Example

FloatingActionButton in Android
 

A quick tour of the FloatingActionButton widget

A new component appeared in Android along with the Library of Material Design. It is used to ensure that the most important functions of your application are always visible and available on the screen in one tap (click). Also, the widget is often paired with a SnackBar.FloatingActionButtonFloatingActionButton

FloatingActionButton integration in application

Because the FloatingActionButton is part of the Material Design Library, you need to add it to the application dependencies. In the file, add the following line in the section:build.gradle (Module: app)dependencies

The version in your application may differ, so if the development environment swears, try writing like this:

And Android Studio will tell you the right version.

The widget itself looks like this:FloatingActionButton

Important points:

  • FloatingActionButton is an inheritor of the ImageView class. The attribute lets us know that right away.android:src
  • Note the attribute that is used to specify that the widget rise above the main layout, dropping the shadow when clicked with the .app:elevationapp:pressedTranslationZ

Widget layout FloatingActionButton

 

FloatingActionButton is used in the layout of the . The CoordinatorLayout layout gives you flexibility in customization and helps you quickly communicate between child views.CoordinatorLayout

Please note: it is advisable to always use the latest versions of Android Studio and project build tools, otherwise at some point an unpleasant error may appear when building the project.

If you're using the latest versions of your development environment and build tools, Android Studio integrates it into your app when you create your project. To do this, create a new project as shown here, only use Blank Activity instead of Empty Activity:

FloatingActionButton

After building the project, you will see 2 files in the /res/layout folder:

  • content_main.xml with the root RelativeLayout and TextView for the content of our application.
  • activity_main.xml with the root CoordinatorLayout and toolbar and FloatingActionButton widgets

The contents of the activity_main.xml are presented below:

As you can see from the layout content, activity_main.xml is a container with markup for the app's underlying widgets, including , and the content of our app itself will be in the content_main.xml. We put it in with a single tag.

FloatingActionButton<include/>

In the code, our FloatingActionButton is initialized as follows:

Initializing and installing listeners on is no different from the usual widgets Button, ImageButton, RadioButton or others.FloatingActionButton