Adding Floating Action Button Kotlin

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 Kotlin and Android Studio.
Minimum API: Android 2.1 is API level 7

Adding Floating Action Button (Kotlin)

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.kt

package com.jigopost.myapplication

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

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val mFab = findViewById<FloatingActionButton>(R.id.fab)
        mFab.setOnClickListener {
            Toast.makeText(this@MainActivity, "FAB is clicked...", Toast.LENGTH_LONG).show()
        }

    }
}

Leave a Reply