Floating Action Button (FAB) Code Snippet for Android Studio


Welcome. In this tutorial you will learn how to add a Floating Action Button in your Android Devices.

Android Floating Action Button (FAB) Example

Floating Action Button (also known as FAB)  is a special type of button in Android that is generally circular and is displayed at the bottom as a small round button. They are used to trigger special type of action in your app’s UI. In this page you will learn how to add a Floating action button to your android’s UI and also how to perform an operation when the button is tapped.

Inserting the Floating Action Button in your layout

To create a floating action button, just add these lines of code to your XML file:-

Floating action buttons come in two sizes: a default one and a mini size which can be changed with the fabSize attribute.

You can also change other properties of the floating action button like the ripple color using the app:rippleColor attribute or the fab icon, using the android:src attribute.


Adding function for the Button Taps

You can respond to the button taps by adding a setOnClickListener, which will respond to button taps. The source code for example is shown below:-


The above code will create a floating action button and once the user clicks on it, it will display a snackbar on the bottom of the page. You can even add your desired code inside the onClick function.


The image below shows a pink colored floating action button which is placed at the bottom.


Floating action button (Fab) code for Android Studio example

Once the button is pressed, it will display a snackbar at the bottom like this:-


Floating action Button (FAB) for Android Studio


The Complete Code Snippet for above example is given below:-

Java (MainActivity.java)



XML (activity_main.xml)



You can directly copy paste these snippets to your android studio, and they should work perfectly. Just save and run your project.


For a more detailed guide, you can also visit android’s official guide below:-


Comment down below if you are facing any problems.


Also Read:-

Leave a Reply

Your email address will not be published. Required fields are marked *