【发布时间】:2018-04-11 10:21:23
【问题描述】:
我正在尝试使用以下代码设置 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>
【问题讨论】:
-
@Mohamed 但实际上是什么?
-
试试这个:view.setBackgroundColor(ContextCompat.getColor(mcontext, R.color.offer_grey))
-
@ShubhamSrivastava 我更新了我的问题 - 已经在使用 ContextCompat
标签: android android-layout imageview android-imageview