Home » Android » android – setImageResource(int) doesn't work after setBackgroundTintColorList(ColorStateList) FloatingActionButton

android – setImageResource(int) doesn't work after setBackgroundTintColorList(ColorStateList) FloatingActionButton

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have to change FAB state in UtteranceProgressListener callback methods but setImageResource() does nothing when called after setBackgroundTintColorList(). However it does change src image when I comment out setBackgroundTintColorList().

setBackgroundTintColorList();
setImageResource();
//doesn't work

//setBackgroundTintColorList();
setImageResource();
//Now it works.

What’s wrong.

How to&Answers:

I’ve encountered the same problem – I’m guessing it’s a bug. Even though my Fab is visible, call hide() and show() before and after the set, as a workaround.

fun FloatingActionButton.changeFab(@ColorRes colorRes: Int, @DrawableRes imageRes: Int) {
    hide()
    backgroundTintList = ContextCompat.getColorStateList(context, colorRes)
    setImageResource(imageRes)
    show()
}

Bug report: https://issuetracker.google.com/issues/111316656

Answer:

Just an addendum:
In my program the FAB is part of a collapsing toolbar. Changing the icon used to fail after some successful attempts, ending in an empty FAB, maybe due to a race condition bug or state bug in Google’s library. I first removed the setBackgroundTintList(), but contrary to the given example this did not work, i.e. the FAB remained coloured, but empty. So I finally applied ersin-ertan’s great workaround, but in Java, what looks like this:

    mFloatingButton.hide();
    mFloatingButton.setImageResource(...);
    mFloatingButton.setBackgroundTintList(...);
    mFloatingButton.show();