0

I am trying to add a custom view (the portion with red boundary will be replaced with my custom view having a 3 dots loader animation) at the end of a multi-line TextView in my Android app.

enter image description here

I know how to specifically add an ImageView using a SpannableString like this:-

fun addImageToEndOfTheString(text: String, drawableResourceId : Int ,context: Context) : SpannableStringBuilder {
        val drawable = ContextCompat.getDrawable(context, drawableResourceId)!!
        drawable.setBounds(0, 0, 98, 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
    }

But the problem is I have a custom view which I want to place at the end of my TextView. How can I achieve that?

Note : My custom view is a subclass of View.

Rohit Singla
  • 112
  • 2
  • 9

1 Answers1

0

simply: you can't.

in posted example you aren't adding ImageView, you are adding ImageSpan with just drawable, thats very not the same...

Views can't hold/host other Views, you have to use ViewGroup or some subclass

easiest way would be to make some LinearLayout with vertical orientation and two Views: TextView and your custom View. second one may have android:visibility="gone" and you can show it only when needed

snachmsm
  • 17,866
  • 3
  • 32
  • 74
  • but the problem will be my ```CustomView``` will be completely below the ```TextView```. What if there is enough space to show my ```CustomView``` on the line on which the ```TextView``` is ending? I would like to show my ```CustomView``` in that same line. – Rohit Singla Nov 04 '22 at 13:07
  • hard, but "proper" way - your `CustomView` should contain `TextView` inside and you can get access to `textView.getPaint().getTextBounds` - measure text internally and add your `CustomView` in last line if there is a space, if not then put below. some hard math to do in here. "hacky" way would be to [convert your `CustomView` to `Drawable`/`Bitmap`](https://stackoverflow.com/questions/2801116/converting-a-view-to-bitmap-without-displaying-it-in-android) and then you may use it in spans having only `TextView` in layout and in fact no `CustomView` at all, only its look as image in text – snachmsm Nov 04 '22 at 13:33