Programmatically set left drawable in a TextView Programmatically set left drawable in a TextView android android

Programmatically set left drawable in a TextView


You can use setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)

set 0 where you don't want images

Example for Drawable on the left:

TextView textView = (TextView) findViewById(R.id.myTxtView);textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);

Alternatively, you can use setCompoundDrawablesRelativeWithIntrinsicBounds to respect RTL/LTR layouts.


Tip: Whenever you know any XML attribute but don't have clue about how to use it at runtime. just go to the description of that property in developer doc. There you will find Related Methods if it's supported at runtime . i.e. For DrawableLeft


Using Kotlin:

You can create an extension function or just use setCompoundDrawablesWithIntrinsicBounds directly.

fun TextView.leftDrawable(@DrawableRes id: Int = 0) {   this.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)}

If you need to resize the drawable, you can use this extension function.

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)}

To get really fancy, create a wrapper that allows size and/or color modification.

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)}