TextView Drawable compat returns null

Viewed 271

My TextView has Drawable icon associated with it as below:

<androidx.appcompat.widget.AppCompatTextView
    android:id="@+id/tvProfile"
    android:drawableStart="@drawable/ic_menu_profile" />

while trying to tint/colour at runtime the textView's drawable compact, the below attempt returns null. But, the android:drawableLeft returns the drawable instance.

tvProfile.compoundDrawables[0]?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)

Was wondering any solution with android:drawableStart?

2 Answers

Use the compoundDrawablesRelative method:

tvProfile.compoundDrawablesRelative[0]?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)

You can check the doc:

Returns drawables for the start, top, end, and bottom borders.

while the getCompoundDrawables returns drawables for the left, top, right, and bottom borders.

You can achieve like this on kotlin:

fun TextView.setDrawableColor(@ColorRes color: Int) {
      compoundDrawables.filterNotNull().forEach {
          it.colorFilter = PorterDuffColorFilter(getColor(context, color), PorterDuff.Mode.SRC_IN)
    }
}
Related