Adding Floating Action Button (Java)

The Floating Action Button (FAB) is a circular button that triggers primary action in your app’s UI. This tutorial shows you how to add the FAB to your layout, customize some of its appearance, and respond to the button taps. We will show Snackbar on FAB click.
We will use Java and Android Studio.
Minimum API: Android 2.1 is API level 7

Adding Floating Action Button (Java)

Step 1: Create a new project OR Open your project

Step 2: Add design library in build.gradle(Module:app) under dependencies{…}

implementation 'com.android.support:design:27.1.0'

Step 3: Place an image in res>drawable folder

Step 4: Code

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Floating Action Button to show Toast..."
        android:textStyle="bold"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/done"
        android:layout_margin="16dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true" />

</RelativeLayout>

MainActivity.java

package com.jigopost.myapplication;

import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FloatingActionButton mFab = findViewById(R.id.fab);
        mFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "FAB is clicked...", Toast.LENGTH_LONG).show();
            }
        });

    }
}

Step 5: Run Project

Output

Adding Floating Action Button (Java)

Leave a Reply