Android Gotchas: #1 Setting a Drawable on a TextView programmatically
AG is a mini-series on the quirks and idiosyncrasies of Android app development.
Using the XML attribute
I’ve set many drawableLefts
and drawableRights
on TextViews
over the last few years.
<TextView
...
android:drawableLeft="@drawable/ic_viewer_count"/>
Boom. Nice and easy. Never had to set it programatically, yet.
Setting compound drawables
Well, it doesn’t work ¯\(ツ)/¯. After wasting an hour and pulling half my hair out, I noticed I had overlooked an important detail in the JavaDoc.
Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text... The Drawables must already have had Drawable.setBounds called.
Rescue time
Here’s how to do it right:
With IntrinsicBounds
viewerCount.setCompoundDrawablesWithIntrinsicBounds(id, null, null, null)
With DataBinding
@BindingAdapter("drawableLeft")
public static void setDrawableLeft(TextView view, int id) {
view.setCompoundDrawablesWithIntrinsicBounds(id, null, null, null)
}
With a Kotlin Extension
fun TextView.setDrawableLeft(id: Int) {
setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)
}
“The Drawable
’s bounds will be set to its intrinsic bounds.”