Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set tint for an image view programmatically in android?

UPDATE:
@ADev has newer solution in his answer here, but his solution requires newer support library - 25.4.0 or above.


You can change the tint, quite easily in code via:

imageView.setColorFilter(Color.argb(255, 255, 255, 255)); // White Tint

If you want color tint then

imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.MULTIPLY);

For Vector Drawable

imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.SRC_IN);

Most answers refer to using setColorFilter which is not what was originally asked.

The user @Tad has his answer in the right direction but it only works on API 21+.

To set the tint on all Android versions, use the ImageViewCompat:

ImageViewCompat.setImageTintList(imageView, ColorStateList.valueOf(yourTint));

Note that yourTint in this case must be a "color int". If you have a color resource like R.color.blue, you need to load the color int first:

ContextCompat.getColor(context, R.color.blue);

This worked for me

mImageView.setColorFilter(ContextCompat.getColor(getContext(), R.color.green_500));

@Hardik has it right. The other error in your code is when you reference your XML-defined color. You passed only the id to the setColorFilter method, when you should use the ID to locate the color resource, and pass the resource to the setColorFilter method. Rewriting your original code below.

If this line is within your activity:

imageView.setColorFilter(getResources().getColor(R.color.blue), android.graphics.PorterDuff.Mode.MULTIPLY);

Else, you need to reference your main activity:

Activity main = ...
imageView.setColorFilter(main.getResources().getColor(R.color.blue), android.graphics.PorterDuff.Mode.MULTIPLY);

Note that this is also true of the other types of resources, such as integers, bools, dimensions, etc. Except for string, for which you can directly use getString() in your Activity without the need to first call getResources() (don't ask me why).

Otherwise, your code looks good. (Though I haven't investigated the setColorFilter method too much...)


After i tried all methods and they did not work for me.

I get the solution by using another PortDuff.MODE.

imgEstadoBillete.setColorFilter(context.getResources().getColor(R.color.green),PorterDuff.Mode.SRC_IN);

Better simplified extension function thanks to ADev

fun ImageView.setTint(@ColorRes colorRes: Int) {
    ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(ContextCompat.getColor(context, colorRes)))
}

Usage:-

imageView.setTint(R.color.tintColor)