How to Change Floating Action Button Icon Programmatically in Android

The code snippet below will illustrate how to change floating action button icon programmactically in android.

Add floating action button in XML layout file.

Get the instance of the FAB button in the Activity class usingĀ findViewById()method.

Assigned a new drawable icon to android FAB button usingĀ setImageResource()method of the Button class.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:gravity="center"
    android:orientation="vertical">

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@android:drawable/btn_dialog" />
    
</LinearLayout>

MainActivity.java

public class ChangeFabColorActivity extends AppCompatActivity {
    
    private static final String TAG = ChangeFabColorActivity.class.getSimpleName();

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

        FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.floatingActionButton);
        fab.setImageResource(R.drawable.ic_video);
    }
}

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.