Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaFloating Action Button (FAB) in Android with Example

Floating Action Button (FAB) in Android with Example

The floating action button is a bit different button from the ordinary buttons. Floating action buttons are implemented in the app’s UI for primary actions (promoted actions) for the users and the actions under the floating action button are prioritized by the developer. For example the actions like adding an item to the existing list. So in this article, it has been shown how to implement the Floating Action Button (FAB), and also the buttons under the FABs are handled with a simple Toast message. Note that we are going to implement this project using Java language.

Types of Floating Action Button

There are mainly four types of floating action buttons available on Android.

  • Normal/Regular Floating Action Button
  • Mini Floating Action Button
  • Extended Floating Action Button
  • Theming Floating Action Button

In this article let’s discuss the Normal/Regular Floating Action Button and Mini Floating Action Button with a sample example in Android.

Normal/Regular Floating Action Button

Regular FABs are FABs that are not expanded and are regular size. The following example shows a regular FAB with a plus icon.

Floating Action Button Example

 

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Adding Dependency to the build.gradle File

 Go to Module build.gradle file and add this dependency and click on Sync Now button.

implementation 'com.google.android.material:material:1.3.0-alpha02'

Refer to the below image if you can’t get the steps mentioned above:

Gradle file

Step 3: Add the FAB Icons to the Drawable File

For demonstration purposes will import 3 icons in the Drawable folder, and one can import the icons of his/her choice. One can do that by right-clicking the drawable folder > New > Vector Asset. Refer to the following image to import the vector Icon.

Vector Asset

Now select your vector icon

 select your vector icon

Step 4: Working with the XML Files

Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

In the activity_main.xml file add the floating action buttons and invoke the following code. Now invoke the normal FAB. Which is of 56dp radius. We have chained the sub-FABs to the parent FABs so that they are in a single key line. Comments are added inside the code to understand the code in more detail.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">
  
    <!-- This will be the parent Floating Action Button -->
    <!-- After the implementation the Floating Action Button
         at the bottom right corner -->
    <!-- After clicking the above button the following two buttons
         will pop up. So this button is considered as parent FAB -->
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/add_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="16dp"
        android:src="@drawable/ic_add_black_24dp"
        app:fabSize="normal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
  
    <!-- Floating action button for add alarm -->
    <!-- Make sure that you are constraining this
         button to the parent button -->
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/add_alarm_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="24dp"
        app:fabSize="normal"
        app:layout_constraintBottom_toTopOf="@+id/add_fab"
        app:layout_constraintEnd_toEndOf="@+id/add_fab"
        app:layout_constraintStart_toStartOf="@+id/add_fab"
        app:srcCompat="@drawable/ic_add_alarm_black_24dp" />
  
    <!-- Action name text for the add alarm button -->
    <!-- Make sure that you are constraining this Text to
         the add Alarm FAB button -->
    <TextView
        android:id="@+id/add_alarm_action_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="Add Alarm"
        app:layout_constraintBottom_toBottomOf="@+id/add_alarm_fab"
        app:layout_constraintEnd_toStartOf="@+id/add_alarm_fab"
        app:layout_constraintTop_toTopOf="@+id/add_alarm_fab" />
  
    <!-- Floating action button for add person -->
    <!-- Make sure that you are constraining this
         button to the add Alarm FAB button -->
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/add_person_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="24dp"
        app:fabSize="normal"
        app:layout_constraintBottom_toTopOf="@+id/add_alarm_fab"
        app:layout_constraintEnd_toEndOf="@+id/add_alarm_fab"
        app:layout_constraintStart_toStartOf="@+id/add_alarm_fab"
        app:srcCompat="@drawable/ic_person_add_black_24dp" />
  
    <!-- Action name text for the add person button -->
    <!-- Make sure that you are constraining this Text
         to the add Person FAB button -->
    <TextView
        android:id="@+id/add_person_action_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="Add Person"
        app:layout_constraintBottom_toBottomOf="@+id/add_person_fab"
        app:layout_constraintEnd_toStartOf="@+id/add_person_fab"
        app:layout_constraintTop_toTopOf="@+id/add_person_fab" />
</androidx.constraintlayout.widget.ConstraintLayout>


Output UI:

Floating Action Button Example

 

Step 5: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.

Now, we handle all FABs using the setOnClickListener() method you may refer to Handling Click events in Button in Android. In this code, it’s been shown that when sub FABs are to be visible with onClickListener. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
  
public class MainActivity extends AppCompatActivity {
    // Make sure to use the FloatingActionButton for all the FABs
    FloatingActionButton mAddFab, mAddAlarmFab, mAddPersonFab;
  
    // These are taken to make visible and invisible along with FABs
    TextView addAlarmActionText, addPersonActionText;
  
    // to check whether sub FAB buttons are visible or not.
    Boolean isAllFabsVisible;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Register all the FABs with their IDs This FAB button is the Parent
        mAddFab = findViewById(R.id.add_fab);
  
        // FAB button
        mAddAlarmFab = findViewById(R.id.add_alarm_fab);
        mAddPersonFab = findViewById(R.id.add_person_fab);
  
        // Also register the action name text, of all the FABs.
        addAlarmActionText = findViewById(R.id.add_alarm_action_text);
        addPersonActionText = findViewById(R.id.add_person_action_text);
  
        // Now set all the FABs and all the action name texts as GONE
        mAddAlarmFab.setVisibility(View.GONE);
        mAddPersonFab.setVisibility(View.GONE);
        addAlarmActionText.setVisibility(View.GONE);
        addPersonActionText.setVisibility(View.GONE);
  
        // make the boolean variable as false, as all the
        // action name texts and all the sub FABs are invisible
        isAllFabsVisible = false;
  
        // We will make all the FABs and action name texts
        // visible only when Parent FAB button is clicked So
        // we have to handle the Parent FAB button first, by
        // using setOnClickListener you can see below
        mAddFab.setOnClickListener(view -> {
            if (!isAllFabsVisible) {
                // when isAllFabsVisible becomes true make all
                // the action name texts and FABs VISIBLE
                mAddAlarmFab.show();
                mAddPersonFab.show();
                addAlarmActionText.setVisibility(View.VISIBLE);
                addPersonActionText.setVisibility(View.VISIBLE);
  
                // make the boolean variable true as we
                // have set the sub FABs visibility to GONE
                isAllFabsVisible = true;
            } else {
                // when isAllFabsVisible becomes true make
                // all the action name texts and FABs GONE.
                mAddAlarmFab.hide();
                mAddPersonFab.hide();
                addAlarmActionText.setVisibility(View.GONE);
                addPersonActionText.setVisibility(View.GONE);
  
                // make the boolean variable false as we
                // have set the sub FABs visibility to GONE
                isAllFabsVisible = false;
            }
        });
        // below is the sample action to handle add person FAB. Here it shows simple Toast msg.
        // The Toast will be shown only when they are visible and only when user clicks on them
        mAddPersonFab.setOnClickListener(
          view -> Toast.makeText(MainActivity.this, "Person Added", Toast.LENGTH_SHORT
                                ).show());
  
        // below is the sample action to handle add alarm FAB. Here it shows simple Toast msg
        // The Toast will be shown only when they are visible and only when user clicks on them
        mAddAlarmFab.setOnClickListener(
          view -> Toast.makeText(MainActivity.this, "Alarm Added", Toast.LENGTH_SHORT
                                ).show());
    }
}


Kotlin




import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton
  
class MainActivity : AppCompatActivity() {
    // Make sure to use the FloatingActionButton for all the FABs
    private lateinit var mAddFab: FloatingActionButton
    private lateinit var mAddAlarmFab: FloatingActionButton
    private lateinit var mAddPersonFab: FloatingActionButton
  
    // These are taken to make visible and invisible along with FABs
    private lateinit var addAlarmActionText: TextView
    private lateinit var addPersonActionText: TextView
  
    // to check whether sub FAB buttons are visible or not.
    private var isAllFabsVisible: Boolean? = null
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Register all the FABs with their IDs This FAB button is the Parent
        mAddFab = findViewById(R.id.add_fab)
  
        // FAB button
        mAddAlarmFab = findViewById(R.id.add_alarm_fab)
        mAddPersonFab = findViewById(R.id.add_person_fab)
  
        // Also register the action name text, of all the FABs.
        addAlarmActionText = findViewById(R.id.add_alarm_action_text)
        addPersonActionText = findViewById(R.id.add_person_action_text)
  
        // Now set all the FABs and all the action name texts as GONE
        mAddAlarmFab.visibility = View.GONE
        mAddPersonFab.visibility = View.GONE
        addAlarmActionText.visibility = View.GONE
        addPersonActionText.visibility = View.GONE
  
        // make the boolean variable as false, as all the
        // action name texts and all the sub FABs are invisible
        isAllFabsVisible = false
  
        // We will make all the FABs and action name texts
        // visible only when Parent FAB button is clicked So
        // we have to handle the Parent FAB button first, by
        // using setOnClickListener you can see below
        mAddFab.setOnClickListener(View.OnClickListener {
            (if (!isAllFabsVisible!!) {
                // when isAllFabsVisible becomes true make all
                // the action name texts and FABs VISIBLE
                mAddAlarmFab.show()
                mAddPersonFab.show()
                addAlarmActionText.visibility = View.VISIBLE
                addPersonActionText.visibility = View.VISIBLE
  
                // make the boolean variable true as we
                // have set the sub FABs visibility to GONE
                true
            } else {
                // when isAllFabsVisible becomes true make
                // all the action name texts and FABs GONE.
                mAddAlarmFab.hide()
                mAddPersonFab.hide()
                addAlarmActionText.visibility = View.GONE
                addPersonActionText.visibility = View.GONE
  
                // make the boolean variable false as we
                // have set the sub FABs visibility to GONE
                false
            }).also { isAllFabsVisible = it }
        })
        // below is the sample action to handle add person FAB. Here it shows simple Toast msg.
        // The Toast will be shown only when they are visible and only when user clicks on them
        mAddPersonFab.setOnClickListener {
            Toast.makeText(this, "Person Added", Toast.LENGTH_SHORT).show()
        }
  
        // below is the sample action to handle add alarm FAB. Here it shows simple Toast msg
        // The Toast will be shown only when they are visible and only when user clicks on them
        mAddAlarmFab.setOnClickListener {
            Toast.makeText(this, "Alarm Added", Toast.LENGTH_SHORT).show()
        }
    }
}


Output: Run on Emulator

Mini Floating Action Button

Mini FABs are used on smaller screens. Mini FABs can also be used to create visual continuity with other screen elements. The following example shows a mini FAB with a plus icon.

Floating Action Button Example

 

Creating a Mini FAB

Now invoke the mini FAB button. Which is of 40dp radius. All the other things are renamed the same. Only one attribute needs to be changed that is:

app:fabSize="mini"

After doing the changes the output UI looks like this:

app:fabsize="auto"

Note: The FAB can also be made auto resizable by changing the fabSize attribute to auto. This will make FAB size automatically mini and normal according to the window size.

RELATED ARTICLES

Most Popular

Recent Comments