How to programmatically create a Floating Action button in Kotlin

In this android kotlin source code example, we are going to programmatically add a Floating Action button in Kotlin.

You can copy and adopt this source code example to your Kotlin android project without reinventing the wheel.

Below is a step by step source code to programmatically add a Floating Action button in Kotlin

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Button.ButtonActivity9">

</RelativeLayout>

MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.bluapp.kotlinview.R
import com.google.android.material.floatingactionbutton.FloatingActionButton

class ButtonActivity9 : AppCompatActivity() {

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

        val relativeLayout = findViewById(R.id.relativeLayout) as RelativeLayout

        val fab = FloatingActionButton(this)
        val rel = RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        rel.setMargins(15, 15, 15, 15)
        rel.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        rel.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        fab.layoutParams = rel
        fab.setImageResource(android.R.drawable.ic_dialog_email)
        fab.size = FloatingActionButton.SIZE_NORMAL
        relativeLayout.addView(fab)

    }


}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment