Android API 21中未设置ImageView背景颜色

时间:2018-04-11 10:21:23

标签: android android-layout imageview android-imageview

我正在尝试使用以下代码设置imageView的背景颜色:

//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);
}

但是这仅适用于API 21 +

我正在使用AppCompatImageView

有没有办法解决这个问题?

更新

这是我使用的Context.color Kotlin扩展函数:

@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
}

这是布局中的ImageView:

<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" />

这是我的绘画,我用于背景:

<?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>

2 个答案:

答案 0 :(得分:0)

我找到的解决方案不是:

innerCircle.setTint(color);

我应该使用:

 innerCircle.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP));

答案 1 :(得分:-1)

试试这个

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

@Deprecated
public void setBackgroundDrawable(Drawable background) { ... }