Created
January 9, 2018 22:04
-
-
Save aoriani/84b15864b977f0c444bbdfa648792081 to your computer and use it in GitHub Desktop.
Binding adapter to tint ImageViews
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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