如何在 Kotlin 中以编程方式更改浮动操作按钮的背景图像?

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

我使用以下 FloatingActionButton 并使用 xml 设置背景图像。如何在 Kotlin 中以编程方式更改图像?我想将图像 'image-color' 替换为 '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" />

您可以使用setImageDrawable函数。

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