1

I often need to have some piece of dynamic text in a TextView, with some drawable image at the end of it.

I'm having troubles making it look nice when the text needs to span onto 2 lines. I would want the image to go inline with the text.

This is what it looks like:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:text="This is my favourite which has a really long piece of string which will wrap"
    app:drawableEndCompat="@drawable/ic_baseline_favorite_border_24" />

Image not wrapping

This is what I want it to look like:

enter image description here

Drawable End in a TextView, or putting an ImageView next to a TextView doesn't work. Is there an easy way to get this image inline with the text as if it is part of the text?

Zain
  • 37,492
  • 7
  • 60
  • 84
SmallGrammer
  • 893
  • 9
  • 19

1 Answers1

0

Based on the Answer here, thanks to @Linh. And on the VerticalImageSpan

This is manipulated to add a drawable at the end of the text:

TextView extension function:

fun TextView.addImageAtEnd(@DrawableRes imgSrc: Int, imgWidth: Int, imgHeight: Int) {
    val ssb = SpannableStringBuilder(this.text)

    val drawable = ContextCompat.getDrawable(this.context, imgSrc) ?: return
    drawable.mutate()
    drawable.setBounds(
        0, 0,
        imgWidth,
        imgHeight
    )
    ssb.setSpan(
        VerticalImageSpan(drawable),
        length() - 1,
        length(),
        Spannable.SPAN_INCLUSIVE_EXCLUSIVE
    )
    this.setText(ssb, TextView.BufferType.SPANNABLE)
}

Usage:

textView2.text = "This is my favourite which has a really long piece of string which will wrap "

textView2.addImageAtEnd(
    R.drawable.heart_outline,
    resources.getDimensionPixelOffset(R.dimen.dp_30),
    resources.getDimensionPixelOffset(R.dimen.dp_30)
)

Result:

enter image description here

Zain
  • 37,492
  • 7
  • 60
  • 84