使用Kotlin:
您可以创建扩展功能或直接使用setCompoundDrawablesWithIntrinsicBounds
。
fun TextView.leftDrawable(@DrawableRes id: Int = 0) {
this.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)
}
如果需要调整可绘制对象的大小,则可以使用此扩展功能。
textView.leftDrawable(R.drawable.my_icon, R.dimen.icon_size)
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) {
val drawable = ContextCompat.getDrawable(context, id)
val size = resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
this.setCompoundDrawables(drawable, null, null, null)
}
为了真正实现幻想,请创建一个允许大小和/或颜色修改的包装器。
textView.leftDrawable(R.drawable.my_icon, colorRes = R.color.white)
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int = 0, @ColorInt color: Int = 0, @ColorRes colorRes: Int = 0) {
val drawable = drawable(id)
if (sizeRes != 0) {
val size = resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
}
if (color != 0) {
drawable?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
} else if (colorRes != 0) {
val colorInt = ContextCompat.getColor(context, colorRes)
drawable?.setColorFilter(colorInt, PorterDuff.Mode.SRC_ATOP)
}
this.setCompoundDrawables(drawable, null, null, null)
}