How to Add a Floating Action Button Programmatically in Android

Just like any other View in android, floating action button can be added inside a parent ViewGroup by instantiating the floating action button and then useĀ addView()method of its parent to add the button to its parent.

If you are also interested on how to add and position a button programmatically inside its parent, I will suggest your read my previous post on how to position a button in RelativeLayout programmatically.

activity_main.xml

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

</RelativeLayout>

MainActivity.java

import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.RelativeLayout;


public class ProgrammaticallyFabActivity extends AppCompatActivity {
    
    private RelativeLayout relativeLayout;

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

        relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);

        FloatingActionButton fab = new FloatingActionButton(this);
        RelativeLayout.LayoutParams rel = new 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.setLayoutParams(rel);
        fab.setImageResource(android.R.drawable.ic_dialog_email);
        fab.setSize(FloatingActionButton.SIZE_NORMAL);
        
        relativeLayout.addView(fab);
    }
}

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

 

Add a Comment