0

I am trying to set background color of my imageView with this code:

//Here is where i am using this custom view(WITH KOTLIN)
myCustomiew.setIconBackgroundColor(color(R.color.color_primary))

//This is inside the custom view(WITH JAVA)
public void setIconBackgroundColor(@ColorInt int color) {
    this.tintIconBackgroundLayer(id.innerCircle, color);
}

private void tintIconBackgroundLayer(@IdRes int layerId, @ColorInt int color) {
    Drawable innerCircle = this.iconBackground.findDrawableByLayerId(layerId);
    innerCircle.setTint(color);
    this.iconBackground.setDrawableByLayerId(layerId, innerCircle);
    this.iconImageView.setBackground(this.iconBackground);
}

However this works only on API 21+

I am using AppCompatImageView

Is there a way to resolve this issue?

UPDATE:

This is my Context.color Kotlin extension function which I use:

@ColorInt
fun Context.color(@ColorRes res: Int, @IntRange(from = 0x0, to = 0xFF) alpha: Int = -1): Int {
  var color = ContextCompat.getColor(this, res)
 if (alpha != -1) {
color = ColorUtils.setAlphaComponent(color, alpha)
 }
return color
}

And here is my ImageView in layout:

<android.support.v7.widget.AppCompatImageView
    android:id="@+id/iconImageView"
    android:layout_width="90dp"
    android:layout_height="90dp"
    android:layout_alignTop="@+id/contentCard"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="-45dp"
    android:background="@drawable/bg_voucher_icon_large"
    android:elevation="6dp"
    android:outlineProvider="none"
    android:scaleType="centerInside"
    tools:src="@drawable/_other" />

This is my drawable, which i am using for background:

<?xml version="1.0" encoding="utf-8"?>
<layer-list 
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/outerCircle">
<shape android:shape="oval">
  <solid android:color="@android:color/white" />
</shape>
</item>
<item
android:id="@+id/innerCircle"
android:bottom="6dp"
android:left="6dp"
android:right="6dp"
android:top="6dp">
<shape android:shape="oval">
  <solid android:color="@android:color/holo_blue_dark" />
</shape>
</item>
</layer-list>
K.Os
  • 5,123
  • 8
  • 40
  • 95

2 Answers2

0

The solution that I've found is instead of:

innerCircle.setTint(color);

I should use:

 innerCircle.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP));
K.Os
  • 5,123
  • 8
  • 40
  • 95
-1

Try this

    public void setBackground(Drawable background) {
    //noinspection deprecation
    setBackgroundDrawable(background);
}

@Deprecated
public void setBackgroundDrawable(Drawable background) { ... }
Anonymous
  • 2,184
  • 15
  • 23
Awadhesh
  • 1
  • 3