Android Extended Floating Action Button Using Kotlin

In this post, we are going to learn about android extended floating action button using Kotlin with example. We will go through different attributes of extended floating action button that can be used to customise it.

Output

Tutorialwing Android Extended Floating Action Button Using Kotlin With Example

Source Code

Download ExtendedFloatingActionButton Source Code

Getting Started

A floating action button and an extended floating button are like below –
Tutorialwing Android Floating Action Button Example

A Floating Action Button represents primary action of screen. We have covered this separate tutorial. Visit here to know more about floating action button.

Extended floating action button is used when we want to show some sub menus that can be used to perform some actions.

As per official documentation,
Extended floating action buttons are used for a special type of promoted action. They are distinguished by an icon and a text floating above the UI and have special motion behaviours related to morphing, launching, and the transferring anchor point.

Extended floating action buttons may have icon and text, but may also hold just an icon or text.

Creating New Project

Follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as ExtendedFloatingActionButton. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?
Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access widget in Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding = true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding = true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Basic Extended Floating Action control is –

<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
    android:id="@+id/extended_fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:layout_gravity="bottom|right"
    android:contentDescription="CONTENT_DESCRIPTION"
    android:text="LABEL_FOR_BUTTON"
    app:icon="ICON_REFERENCE"/>

This is basic extended floating button which we use in project, along with other floating buttons, to show ui we desired which shrinks and expands on click.

Now, we will use it in our project.

Using Extended Floating Action Button in Kotlin

Open res/layout/activity_main.xml file, add below code in it –

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:ignore="HardcodedText">

    <com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
        android:id="@+id/fab_menu_actions"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="16dp"
        android:backgroundTint="@color/purple_200"
        android:text="@string/actions"
        app:icon="@drawable/ic_add_circle"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab_menu_add_alarm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="24dp"
        android:backgroundTint="@color/purple_200"
        android:contentDescription="Menu Alarm"
        android:visibility="gone"
        app:fabSize="normal"
        app:layout_constraintBottom_toTopOf="@+id/fab_menu_actions"
        app:layout_constraintEnd_toEndOf="@+id/fab_menu_actions"
        app:srcCompat="@drawable/ic_alarm" />

    <TextView
        android:id="@+id/fab_menu_add_alarm_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="@string/add_alarm"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="@+id/fab_menu_add_alarm"
        app:layout_constraintEnd_toStartOf="@+id/fab_menu_add_alarm"
        app:layout_constraintTop_toTopOf="@+id/fab_menu_add_alarm" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab_menu_add_person"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="24dp"
        android:backgroundTint="@color/purple_200"
        android:contentDescription="Menu Person"
        android:visibility="gone"
        app:fabSize="normal"
        app:layout_constraintBottom_toTopOf="@+id/fab_menu_add_alarm"
        app:layout_constraintEnd_toEndOf="@+id/fab_menu_add_alarm"
        app:layout_constraintStart_toStartOf="@+id/fab_menu_add_alarm"
        app:srcCompat="@drawable/ic_person" />

    <TextView
        android:id="@+id/fab_menu_add_person_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="@string/add_person"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="@+id/fab_menu_add_person"
        app:layout_constraintEnd_toStartOf="@+id/fab_menu_add_person"
        app:layout_constraintTop_toTopOf="@+id/fab_menu_add_person" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here, we have used –

  • One Extended Floating Action Button
  • Two Floating Action Buttons
  • Two TextViews

One textview and one floating action button represents one action.

In above xml file, we have used one extended floating action button that show and hide two actions, created by one textView and one floating action button each, when clicked on it.

Access Extended Floating Action Button Programmatically

Open MainActivity.kt file. Then, add below code in it.

package com.tutorialwing.extendedfloatingactionbutton

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.tutorialwing.extendedfloatingactionbutton.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity(), View.OnClickListener {

	private lateinit var binding: ActivityMainBinding

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		binding = ActivityMainBinding.inflate(layoutInflater)
		val view = binding.root
		setContentView(view)

		setupFabButtons()
	}

	private fun setupFabButtons() {
		binding.fabMenuActions.shrink()
		binding.fabMenuActions.setOnClickListener(this)
		binding.fabMenuAddAlarm.setOnClickListener(this)
		binding.fabMenuAddPerson.setOnClickListener(this)
	}

	override fun onClick(view: View?) {
		when (view?.id) {
			R.id.fab_menu_actions -> {
				expandOrCollapseFAB()
			}
			R.id.fab_menu_add_alarm -> {
				showToast("Hello From Add Alarm Button")
			}
			R.id.fab_menu_add_person -> {
				showToast("Hello From Add Person Button")
			}
		}
	}

	private fun showToast(message: String) {
		Toast.makeText(baseContext, message, Toast.LENGTH_SHORT).show()
	}

	private fun expandOrCollapseFAB() {
		if (binding.fabMenuActions.isExtended) {
			binding.fabMenuActions.shrink()
			binding.fabMenuAddAlarm.hide()
			binding.fabMenuAddAlarmText.visibility = View.GONE
			binding.fabMenuAddPerson.hide()
			binding.fabMenuAddPersonText.visibility = View.GONE
		} else {
			binding.fabMenuActions.extend()
			binding.fabMenuAddAlarm.show()
			binding.fabMenuAddAlarmText.visibility = View.VISIBLE
			binding.fabMenuAddPerson.show()
			binding.fabMenuAddPersonText.visibility = View.VISIBLE
		}
	}
}

Here,

  • setupFabButtons(): This method –
    1. Shrinks extended floating action button by default. It means when you run or open the app, this button will be in collapsed state.
    2. Sets click listener on
      – one Extended Floating Action Button
      – two Floating Action Buttons
  • onClick(view: View?): This method is called when-ever any button is clicked. It matches the id of view and perform task accordingly.
  • showToast(message: String): This method shows given message as toast.
  • expandOrCollapseFAB(): This method shows and hides action buttons when clicked on extended floating action button

Adding Icons in Drawable Folder

We need to add some icons in drawable that are being used in activity_main.xml file. Here, we have added some vector icons. Visit post to know more about detailed steps on how to add vector assets in drawable folder using vector asset studio

You can also use bitmap image in any format e.g. .png, .jpeg, .jpg etc.
In this article, we have used vector image. Visit post to know more about difference between bitmap image and vector image.
However, if you want to use bitmap image, you can visit post to know how to add bitmap image using image asset studio.

Follow steps below to add some vector icons we have used in our project.

  • Open res/drawable folder.
  • There are 3 icons we are using in our project.
    1. Create ic_add_circle.xml file in res/drawable folder. Then, add below code in it –

      <vector xmlns:android="http://schemas.android.com/apk/res/android"
          android:width="24dp"
          android:height="24dp"
          android:viewportWidth="24"
          android:viewportHeight="24"
          android:tint="?attr/colorControlNormal">
        <path
            android:fillColor="@android:color/white"
            android:pathData="M13,7h-2v4L7,11v2h4v4h2v-4h4v-2h-4L13,7zM12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM12,20c-4.41,0 -8,-3.59 -8,-8s3.59,-8 8,-8 8,3.59 8,8 -3.59,8 -8,8z"/>
      </vector>
      
    2. Create ic_alarm.xml file in res/drawable folder. Then, add below code in it –

      <vector xmlns:android="http://schemas.android.com/apk/res/android"
          android:width="24dp"
          android:height="24dp"
          android:viewportWidth="24"
          android:viewportHeight="24"
          android:tint="?attr/colorControlNormal">
        <path
            android:fillColor="@android:color/white"
            android:pathData="M22,5.72l-4.6,-3.86 -1.29,1.53 4.6,3.86L22,5.72zM7.88,3.39L6.6,1.86 2,5.71l1.29,1.53 4.59,-3.85zM12.5,8L11,8v6l4.75,2.85 0.75,-1.23 -4,-2.37L12.5,8zM12,4c-4.97,0 -9,4.03 -9,9s4.02,9 9,9c4.97,0 9,-4.03 9,-9s-4.03,-9 -9,-9zM12,20c-3.87,0 -7,-3.13 -7,-7s3.13,-7 7,-7 7,3.13 7,7 -3.13,7 -7,7z"/>
      </vector>
      
    3. Create ic_person.xml file in res/drawable folder. Then, add below code in it –

      <vector xmlns:android="http://schemas.android.com/apk/res/android"
          android:width="24dp"
          android:height="24dp"
          android:viewportWidth="24"
          android:viewportHeight="24"
          android:tint="?attr/colorControlNormal">
        <path
            android:fillColor="@android:color/white"
            android:pathData="M13,8c0,-2.21 -1.79,-4 -4,-4S5,5.79 5,8s1.79,4 4,4S13,10.21 13,8zM11,8c0,1.1 -0.9,2 -2,2S7,9.1 7,8s0.9,-2 2,-2S11,6.9 11,8zM1,18v2h16v-2c0,-2.66 -5.33,-4 -8,-4S1,15.34 1,18zM3,18c0.2,-0.71 3.3,-2 6,-2c2.69,0 5.78,1.28 6,2H3zM20,15v-3h3v-2h-3V7h-2v3h-3v2h3v3H20z"/>
      </vector>
      

Adding Hardcoded text in strings.xml File

Open res/values/strings.xml file. Then, add below code into it –

<resources>
    <string name="app_name">Extended Floating Action Button</string>
    <string name="actions">Actions</string>
    <string name="add_alarm">Add Alarm</string>
    <string name="add_person">Add Person</string>
</resources>

Then, run app. We will get output as shown below –

Leave a Reply