Search code examples
androidkotlinfloating-action-buttonmaterial-components-android

How to change the background image of Floating Action Button programatically in Kotlin?


I use the following FloatingActionButton and I have set the background image using xml. How can I change the image programmatically in Kotlin? I want to replace the image 'image-color' with 'image-bw'.

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/image_fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/image-color"
    android:scaleType="center"
    app:maxImageSize="56dp"
    app:tint="@null"
    app:layout_anchor="@id/bottom_appbar"
    android:contentDescription="Categories" />

Solution

  • You can use the setImageDrawable function.

    imageFab.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.your_drawable))