Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert ImageView at the end of multiline TextView?

Maybe it's a stupid question, but I cant find a way to inser small image at the end of second line of TextView. Image is always appears to the right of whole textview, not the line end.

I want to insert image like this:

TextTextTextTextTextTextTextTextTextText
TextTextTextText. <ImageView>

What I am getting is:

TextTextTextTextTextTextTextTextTextText  <ImageView>
TextTextTextText. 

I hope there is way to do it.

Src:

<RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TESTESTESTESTESTESTESTESTESTESTESTESTES"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#FFFFFF" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/tv"
            android:src="@drawable/icon" />
    </RelativeLayout>
like image 333
Sver Avatar asked Oct 27 '11 09:10

Sver


2 Answers

You can add the image to end of the string without using imageview like below;

fun addImageToEndOfTheString(text: String, drawableResourceId : Int ,context: Context) : SpannableStringBuilder {
    val drawable = ContextCompat.getDrawable(context, drawableResourceId)!!
    drawable.setBounds(14, 0, 64, 50)
    val rocketImageSpan = ImageSpan(drawable, ImageSpan.ALIGN_BASELINE)

    val ssBuilder = SpannableStringBuilder(text)

    ssBuilder.setSpan(
        rocketImageSpan,
        text.length - 1,
        text.length,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )

    return ssBuilder
}

and call it like;

textView.text = addImageToEndOfTheString("Your text is here", R.drawable.ic_your_image, context!!)

The image will placed end of the text

like image 130
oguzhan Avatar answered Sep 28 '22 20:09

oguzhan


Kotlin extension on the TextView class

/**
 * Creates a StringSpan using the text from the TextView itself and it also adds an ImageSpan at the
 * end of the last line of the TextView.
 * This basically allows us to set a drawable at the end of the TextView text.
 */
fun TextView.setImageSpanAtTheEnd(context: Context, @DrawableRes drawableRes: Int) {
    text = SpannableString("$text ").apply {
        val d = ContextCompat.getDrawable(context, drawableRes) ?: throw RuntimeException("Drawable not found!")
        d.setBounds(0, 0, d.intrinsicWidth, d.intrinsicHeight)
        setSpan(ImageSpan(d, ImageSpan.ALIGN_BASELINE), text.length, text.length+1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
    }
}

Just call it after you set the text on the TextView and that's it.

like image 44
4gus71n Avatar answered Sep 28 '22 19:09

4gus71n