TextView Drawable 兼容 returns null
TextView Drawable compat returns null
我的 TextView 有如下关联的 Drawable 图标:
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/tvProfile"
android:drawableStart="@drawable/ic_menu_profile" />
在运行时尝试 tint/colour textView 的可绘制压缩,下面的尝试 returns 为空。但是,android:drawableLeft
returns 可绘制实例。
tvProfile.compoundDrawables[0]?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
想知道 android:drawableStart
有什么解决方案吗?
你可以在 kotlin 上这样实现:
fun TextView.setDrawableColor(@ColorRes color: Int) {
compoundDrawables.filterNotNull().forEach {
it.colorFilter = PorterDuffColorFilter(getColor(context, color), PorterDuff.Mode.SRC_IN)
}
}
使用compoundDrawablesRelative
方法:
tvProfile.compoundDrawablesRelative[0]?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
您可以查看 doc:
Returns drawables for the start
, top
, end
, and bottom
borders.
而 getCompoundDrawables
returns 可绘制对象用于 left
、top
、right
和 bottom
边框。
我的 TextView 有如下关联的 Drawable 图标:
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/tvProfile"
android:drawableStart="@drawable/ic_menu_profile" />
在运行时尝试 tint/colour textView 的可绘制压缩,下面的尝试 returns 为空。但是,android:drawableLeft
returns 可绘制实例。
tvProfile.compoundDrawables[0]?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
想知道 android:drawableStart
有什么解决方案吗?
你可以在 kotlin 上这样实现:
fun TextView.setDrawableColor(@ColorRes color: Int) {
compoundDrawables.filterNotNull().forEach {
it.colorFilter = PorterDuffColorFilter(getColor(context, color), PorterDuff.Mode.SRC_IN)
}
}
使用compoundDrawablesRelative
方法:
tvProfile.compoundDrawablesRelative[0]?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
您可以查看 doc:
Returns drawables for the
start
,top
,end
, andbottom
borders.
而 getCompoundDrawables
returns 可绘制对象用于 left
、top
、right
和 bottom
边框。