Toggle FloatingActionButton Icon when Clicking On It

Viewed 5847

I have two drawable pictures, initially FAB is set to R.drawable.icon1, I want to set it to R.drawable.icon2 when clicking on it, and setting it back to icon1 when clicking one more time on it and so on...

Is there a way to do that?

Any help is appreciated!

2 Answers

I have created the following extension function for Kotlin to make the operation easier.

fun FloatingActionButton.icon(@DrawableRes id: Int = 0) {
    setImageResource(id)
}

fun FloatingActionButton.backgroundColor(@ColorRes colorRes: Int = 0) {
    backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(context, colorRes))
}

fun FloatingActionButton.iconColor(@ColorRes colorRes: Int = 0) {
    imageTintList = ColorStateList.valueOf(ContextCompat.getColor(context, colorRes))
}

Sample:

var flag = true

binding.fabToggleService.setOnClickListener {
    flag = !flag

    if (flag) {
        binding.fabToggleService.apply {
            icon(R.drawable.ic_round_stop_24)
            iconColor(R.color.white)
            backgroundColor(R.color.md_red_400)

    } else {
        binding.fabToggleService.apply {
            icon(R.drawable.ic_round_play_arrow_24)
            iconColor(R.color.white)
            backgroundColor(R.color.md_blue_400)
    }

}

You can see the action live, see comment with link of one of my apps

Related