Creating a FloatingActionButton in Android

- Andrés Cruz

En español

Creating a FloatingActionButton in Android

The Floating Action Button or floating button is used for all kinds of main actions in an Android application; in this post we will see how to use this button from the support library using Android Studio as an IDE that is part of the Material Design that is part of the new design of our UI as follows:

implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support:design:28.0.0'

Remember to check the SDK level when you incorporate these lines with the current one.

Floating Action Button in Material Design

As the official Google documentation says about the floating button in Material Design, a float action button is a special round-shaped button defined to stand out throughout the app, in which we define the main action for that particular window; this button, as we indicated, is characterized by having a circular shape and an icon with a color that contrasts with the color of the button; sometimes it has the ability to be animable, change shape, interact with other elements, etc.

Instantiating our float button in Android Studio

With the support library already configured, we can use Android's floating button; the FloatingActionButton or the floating button in Android is a fundamental element in Google's Material Design that we have been able to use from Android Studio for a long time; the Float Action Button comes in two sizes; one of 56dp that is the default and another thumbnail that comes in 24dp; in both Java and Kotlin, the floating button has been using the FloatingActionButton class and in the layout or XML in general it is used by android.support.design.widget.FloatingActionButton to use the floating button within the layout we use the following line:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/my_fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    android:src="@drawable/ic_alert_circle_white_36dp" />

Here we already have known attributes to define the width and the height by means of android:layout_width and android:layout_height respectively and the android:src we define an icon; You can download and generate your own icons on the Material Design Icons website:

materialdesignicons

Or from Android Studio itself from the latest versions we can create our own icons to work on the interface in general easily; for this we position ourselves on the drawable folder, right click, Image Asset and then start creating your buttons:

Crear icono Android Studio

With the android:layout_gravity attribute we are placing the icon in the bottom left corner (end); It is also recommended to use the 16dp margin for when the element will be floating in the lower right corner of the screen, if you have it centered in a container, it would not be necessary to apply the margin.

Although if you are going to use multiple instances of a floating button in several views, it is recommended that you place it in the corresponding file; the dimensions.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="fab_margin">16dp</dimen>
</resources>

Other very important attributes are app:fabSize to indicate the size of the floating button that would be normal for a 56dp size or mini for a 24dp size; we also have the app:backgroundTint to assign a background color to the button:

fab dos tamaños

Using the Floating action button from our activity or component

To use the floating button or any other component such as FrameLayout from the main activity, in Java it is mandatory to make the reference:

FloatingActionButton my_fab = (FloatingActionButton) findViewById(R.id.my_fab)

In Kotlin, we don't have to make that reference (it's optional):

val my_fab = findViewById<View>(R.id.my_fab) as FloatingActionButton

But we can also consult it directly from the id of the element that is referenced in the layout; for our example it would simply be to use my_fab without the need to use the previous line:

Floating action button with the OnClickListener

The next thing we have to do is find out what events this floating action button has, just like the Button element in Android, floating buttons have an OnClickListener event; in Java it would be:

my_fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
       Snackbar.make(view, "Tocaste el FAB", Snackbar.LENGTH_LONG).show();
            }
        });

And in Kotlin it would be something like the following:

my_fab.setOnClickListener(object : View.OnClickListener() {
   fun onClick(view: View) {
       Snackbar.make(view, "Tocaste el FAB", Snackbar.LENGTH_LONG).show()
   }
})

In the end, we have a screen like the following:

float action button default

Of course, here we perform a simple functionality of showing a Snackbar; you will already give it the behavior or functionality that you want.

To change the color of the button programmatically we have the setBackgroundTintList() method.

Climb animations on the Floating Action Button

Like almost any visual element in Android, buttons can be animated using any geometric transformation as well as opacity, and combine it as you see fit; here we will show you how to make a couple of simple animations, the first one we will see is to scale the button which, for the functional purposes of this example, disappears indicating that the scale value is zero; finally the example:

final Interpolator interpolador = AnimationUtils.loadInterpolator(getBaseContext(),
       android.R.interpolator.fast_out_slow_in);

my_fab.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {

       my_fab.animate()
               .scaleX(0)
               .scaleY(0)
               .setInterpolator(interpolador)
               .setDuration(600)
               .setListener(new Animator.AnimatorListener() {
                   @Override
                   public void onAnimationStart(Animator animation) {

                   }

                   @Override
                   public void onAnimationEnd(Animator animation) {
                       my_fab.animate()
                               .scaleY(1)
                               .scaleX(1)
                               .setInterpolator(interpolador)
                               .setDuration(600)
                               .start();
                   }

                   @Override
                   public void onAnimationCancel(Animator animation) {

                   }

                   @Override
                   public void onAnimationRepeat(Animator animation) {

                   }
               });

       Snackbar.make(view, "Tocaste el FAB", Snackbar.LENGTH_LONG).show();
   }
});

We must define a tween to indicate the animation tween and then we use the animate() method and other properties to define what we want to do, as well as the listener methods (setListener) that are executed even when the animation starts onAnimationStart when it ends animation onAnimationEnd or animation onAnimationCancel is canceled among others.

 

How you see the code to scale is very similar to the one already discussed in the previous entry on Android animations:

In Kotlin it would be something like the following:

val interpolador = AnimationUtils.loadInterpolator(baseContext,
       android.R.interpolator.fast_out_slow_in)

my_fab.setOnClickListener { view ->
   my_fab.animate()
           .rotation(180f)
           .setInterpolator(interpolador)
           .setDuration(600)
           .setListener(object : Animator.AnimatorListener {
               override fun onAnimationStart(animation: Animator) {

               }

               override fun onAnimationEnd(animation: Animator) {
                   my_fab.animate()
                           .rotation(0f)
                           .setInterpolator(interpolador)
                           .setDuration(600)
                           .start()
               }

               override fun onAnimationCancel(animation: Animator) {

               }

               override fun onAnimationRepeat(animation: Animator) {

               }
           })

   Snackbar.make(view, "Tocaste el FAB", Snackbar.LENGTH_LONG).show()
}

And we get something like the following:

escala float action button default

Rotation animations on the Floating Action Button

If, on the other hand, we want to perform a rotation, we can start from the previous code but vary the scaleX and scaleY methods respectively by rotation and the degree of rotation, which for this example is 180 (.rotation(180)):

rotación float action button default

Positioning on the edge of the containers

Another very interesting utility that can be placed on floating buttons is that they float or be located in the middle of another container, that is, the positioning of the Floating Action Button depends on another container; for this we must take into consideration only 3 attributes and vary their values depending on what we want; the first thing we must do (although the order does not matter) is to indicate the id of the element that depends on the position of the floating button; for this it is the following attribute with the value of the id of a container app:layout_anchor="@+id/contenedor_detalle_item".

Now we must indicate the alignment if we want it to float up, down, etc; the following rule: app:layout_anchorGravity="top|end" we indicate that we want it to be aligned at the beginning (at the top) to the left (at the end -end-).

Finally we can specify another attribute with which we indicate if we want to position it at the end of the container, at the beginning or between the two, which would be in the middle (center_vertical) http://android:layout_gravity="center_vertical|start".

Finally the complete code of the view:

<?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.support.design.widget.AppBarLayout
       android:id="@+id/app_bar"
       android:layout_width="match_parent"
       android:layout_height="200dp"
       android:fitsSystemWindows="true">

       <android.support.design.widget.CollapsingToolbarLayout
           android:id="@+id/toolbar_layout"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:fitsSystemWindows="true"
           app:layout_scrollFlags="scroll|exitUntilCollapsed">

           <android.support.v7.widget.Toolbar
               android:id="@+id/toolbar"
               android:layout_width="match_parent"
               android:layout_height="60dp"
               app:layout_collapseMode="pin"/>

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

   <android.support.v4.widget.NestedScrollView
       android:id="@+id/contenedor_detalle_item"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       app:layout_behavior="@string/appbar_scrolling_view_behavior" />

   <android.support.design.widget.FloatingActionButton
       android:id="@+id/my_fab"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="center_vertical|start"
       android:layout_margin="16dp"
       android:src="@drawable/ic_alert_circle_white_36dp"
       app:layout_anchor="@+id/contenedor_detalle_item"
       app:layout_anchorGravity="top|end" />

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

And it would look like the following:

borde de contenedor de float action button default

Turning the Floating Action Button into a Toolbar

The Floating Action Button (or in English FloatingActionButton) whose image you can see at the beginning of this post, in my opinion is one of the most attractive elements of Material Design and a few versions of support libraries ago, Google has incorporated it together with multiple elements of Material Design.

Natively, or with the support library, we cannot convert a floating button to a toolbar; for this we are going to use a support library that you can download at the following link:

<com.github.rubensousa.floatingtoolbar.FloatingToolbar
   android:id="@+id/floatingToolbar"
   android:layout_width="match_parent"
   android:layout_height="70dp"
   android:layout_gravity="bottom"
   app:floatingMenu="@menu/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="@drawable/ic_alert_circle_white_24dp" />

As we can see, we create our own element of the library and the floating button that we have used up to now, in addition to the FloatingToolbar we associate a menu that for this example is the following:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_unread"
        android:icon="@drawable/ic_alert_circle_white_24dp"
        android:title="Mark unread"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_copy"
        android:icon="@drawable/ic_alert_circle_white_24dp"
        android:title="Copy"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_google"
        android:icon="@drawable/ic_alert_circle_white_24dp"
        android:title="Google+"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_facebook"
        android:icon="@drawable/ic_alert_circle_white_24dp"
        android:title="Facebook"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_twitter"
        android:icon="@drawable/ic_alert_circle_white_24dp"
        android:title="Twitter"
        app:showAsAction="ifRoom" />
</menu>

Which is located in the res folder and has an XML extension.

And from our activity:

final FloatingToolbar mFloatingToolbar = (FloatingToolbar) findViewById(R.id.floatingToolbar); final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); mFloatingToolbar.attachFab(fab);

We simply reference both elements and bind the floating button to the Toolbar.

Finally we get:

float action button y toolbar

Apart from this bookstore there are many others that you can consult

If you don't know what Material Design is, see the following link: Material Design.

If you want to know what are the changes that the new and previous revisions of the support libraries incorporate, see the following link: Support Library.

Why use the FloatingActionButton?

The FloatingActionButton is used for all kinds of main actions in an Android application and in this post we will see how to use this button from the support library using Android Studio as an IDE.

Incorporating the dependencies in our Gradle

As I had commented in the previous post about Android Studio, to link the different libraries or modules from other developers (in this case the support library created by Google in its multiple versions) in our projects it is necessary to place them in our /app/ file. build.gradle the following dependency:

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

Once modified, it is necessary for Android Studio to synchronize to download the different built-in modules; although the synchronization is done automatically:

Sincronización del gradle

Thanks to the previous dependencies, we will be able to incorporate different characteristics of Material Design; such as the following:

  • Navigation View
  • Floating labels
  • Floating Action Button
  • Snackbar
  • Tabs
  • CoordinatorLayout, motion y scrolling
  • Among many other changes that you can check at the following link: Android Design Support Library

Creating our FloatingActionButton from the layout (XML)

Once the necessary dependency is placed, we can start working with the Material Design, specifically our case of interest the Floating Action Button (FloatingActionButton); Let's put the following XML inside some layout; For example, the activity_main.xml so that it looks like this:

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/record_fab"
        style="@style/FloatingActionButtonStyle"
        android:src="@mipmap/device_access_mic"
        app:backgroundTint="@color/color_primary" />

</RelativeLayout>

The app:backgroundTint attribute specifies the color of the FloatingActionButton defined in the values/color.xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <color name="color_primary">#FF5722</color>
</resources>

Now, if we take a tour of the Design mode or the Text mode that also incorporates a detail view, we will see our FloatingActionButton:

floatingActionButton en android Studio

Up to now we have our fantastic FloatingActionButton in our Android interface and up to here we have done half of the work since by itself and like any other element the FloatingActionButton will not do anything unless we reference it from an Activity or Fragment and indicate the tasks To make.

Referencing and OnClick event of the FloatingActionButton

To reference the FloatingActionButton, use the findViewById method just like any other element:

FloatingActionButton recordFab = (FloatingActionButton) findViewById(R.id.record_fab);

Now we can tie it to the OnClick event through the OnClickListener interface, looking like this:

recordFab.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
       Log.i("TAG", "Hacer algo");
   }
});
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.