Skip to content

Instantly share code, notes, and snippets.

@aoriani
Created January 9, 2018 22:04
Show Gist options
  • Save aoriani/84b15864b977f0c444bbdfa648792081 to your computer and use it in GitHub Desktop.
Save aoriani/84b15864b977f0c444bbdfa648792081 to your computer and use it in GitHub Desktop.
Binding adapter to tint ImageViews
@SuppressLint("NewApi")
@BindingAdapter("android:tint")
public static void setTintCompat(ImageView imageView, @ColorInt int color) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
imageView.setImageTintList(android.databinding.adapters.Converters.convertColorToColorStateList(color));
} else {
final Drawable originalDrawable = imageView.getDrawable();
if (originalDrawable instanceof VectorDrawableCompat) {
VectorDrawableCompat vectorDrawableCompat = (VectorDrawableCompat) originalDrawable;
vectorDrawableCompat.setTint(color);
} else {
Drawable tintedDrawable = tintDrawable(originalDrawable, color);
imageView.setImageDrawable(tintedDrawable);
}
}
}
private static Drawable tintDrawable(@NonNull Drawable drawable, @ColorInt int tintInt) {
drawable = DrawableCompat.wrap(DrawableCompat.unwrap(drawable).mutate());
DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_IN);
DrawableCompat.setTint(drawable, tintInt);
return drawable;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment