使用芬兰湾的科特林:
您可以创建一个扩展函数,或者直接使用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)
}