I have an Activity with some menu items, for which I change the icon colors like this:
private void colorMenuItem(MenuItem item) {
if (item != null) {
Drawable icon = item.getIcon();
if (icon != null) {
icon.setColorFilter(getResources().getColor(R.color.some_color), PorterDuff.Mode.SRC_ATOP);
}
}
}
The icons are white drawable PNG files from the material icon set. This works as expected and the menu items are colored as desired.
However, when I start another activity which makes use of the same drawable resource which was already colored, but in another view (e.g a FAB instead of the menu), the ColorFilter for this view remains. Why is that?
Shouldn't the FAB load the resource file again and shouldn't it be white (or unchanged)?
However, when I start another activity which makes use of the same drawable resource which was already colored, but in another view (e.g a FAB instead of the menu), the ColorFilter for this view remains. Why is that?
That is because the drawable or bitmap has been cached and therefore the next call to the same drawable id will be the same drawable that was already tinted before.
To fix it is to mutate first the drawable before using it to have another instance of it, to prevent it from being cached.
Drawable icon = item.getIcon().mutate(); //mutate it to prevent caching