How to create a Floating Action Button in Android using Kotlin
Android Studio project:
For this example, I will use one basic Android Studio project with one activity MainActivity.kt and its layout file activity_main.xml.
Open your Android Studio, click on Create a new project, choose Empty Activity, click on Next, fill the options and click on Finish to create the project.
By default, it will create one activity file MainActivity.kt and one layout file activity_main.xml.
Building the UI:
Open your activity_main.xml file in Design mode and search for Floating action button in the left search bar. It will show you the widget for Floating action button. Drag and drop it in the main layout UI.
This will open one new window, that will ask to pick a resource for the button.
You can select from any existing resource or you can click on the + button to create one new drawable, image or vector asset.
Now, add the constraints to the floating action button and it will show it if you run the app in a simulator.
Below is the layout file for my project:
<?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"><com.google.android.material.floatingactionbutton.FloatingActionButtonandroid:id="@+id/floatingActionButton"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginEnd="52dp"android:layout_marginBottom="50dp"android:clickable="true"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:srcCompat="@drawable/ic_baseline_add_24" /></androidx.constraintlayout.widget.ConstraintLayout>