3

I have an icon which look like this:icon in my constraint layout.

This is my layout xml for this image view:

<ImageView
        android:id="@+id/vTotalPaidAvatar"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:contentDescription="@null"
        android:src="@drawable/ic_group_ic_total"
        tools:src="@drawable/ic_group_ic_total"
        app:layout_constraintLeft_toLeftOf="@+id/vSettleDebtsLayout"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        app:layout_constraintTop_toTopOf="@+id/vSettleDebtsLayout"
        android:layout_marginTop="16dp"
        android:background="@drawable/avatar_circle" />

As you can see, the icon is just a dollar sign. I set that grey circle as background. The problem is that I need to change color of that background dynamically. The dollar sign need to stay white. My question is, is there any way how to change only the color of background?

Another solution would be to use that circle as next imageview and then change color of that image view. But i think that there could be some more "clear solution for this issue.

Thanks for tips :)

Tom Wayne
  • 1,288
  • 1
  • 12
  • 31

4 Answers4

8

Try:

yourImage.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);

This literally gets background (without src) from ImageView and covers its shape with color. The way the drawable and given color are combining is defined by mode of Porter Duff - here you have more about it.

Community
  • 1
  • 1
paulina_glab
  • 2,467
  • 2
  • 16
  • 25
3

Best way to do it:

public static void colorDrawable(View view, int color) {
    Drawable wrappedDrawable = DrawableCompat.wrap(view.getBackground());
    if (wrappedDrawable != null) {
        DrawableCompat.setTint(wrappedDrawable.mutate(), color);
        setBackgroundDrawable(view, wrappedDrawable);
    }
}

public static void setBackgroundDrawable(View view, Drawable drawable) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
        view.setBackgroundDrawable(drawable);
    } else {
        view.setBackground(drawable);
    }
}
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
Prilaga
  • 818
  • 10
  • 18
2

Well u must try

android:backgroundTint="your color"

in imageview tag

this will do the work

Devam03
  • 141
  • 1
  • 7
0

Did you try android:background="@color/my_color" and through code imageView.setBackgroundColor(Color.rgb(255, 255, 255)); ?

Itiel Maimon
  • 834
  • 2
  • 9
  • 26
  • I need to use that circle as background and then i need to change color of that circle. It is drawable... I can not use only color as a background it would fill all space dedicated to my image view -> (it wouldnt have a circle shape) – Tom Wayne Jul 24 '16 at 10:14