Is There Any Way To Insert An Imagespan In A Textview Without Disrupting The Text?
It seems that in order to add an ImageSpan to a Spannable in Android, I have to actually replace some text with the Image. For example: Spannable span = new SpannableString('Foo im
Solution 1:
Maybe you can add an additional space to be replaced by the ImageSpan. For example,
Spannablespan=newSpannableString("Foo imageplace Bar!");
Drawableandroid= context.getResources().getDrawable(R.drawable.android);
android.setBounds(0, 0, 32,32);
ImageSpanimage=newImageSpan(android, ImageSpan.ALIGN_BASELINE);
span.setSpan(image, 3, 4, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
And you will find the image replace the additional space without disrupting the text.
Solution 2:
You have to know the length of the text, the one after you want to add the image. For example..
Drawableimage= ContextCompat.getDrawable(mContext, android.R.drawable.presence_offline);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
// Replace blank spaces with image iconStringmyText="myText";
inttextLength= myText.length();
SpannableStringsb=newSpannableString(myText + " " + "This is another text");
ImageSpanimageSpan=newImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, textLength, textLength + 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
Solution 3:
If you want to insert Drawable at the end of the text, Drawable is hiding the last character of the text to avoid that add another character at the end of the text and start the drawable at that character.
val myText = "Your text"val span: Spannable = SpannableString(myText+"-")
val android: Drawable = ContextCompat.getDrawable(this, R.drawable.yourDrawable)!!
android.setBounds(0, 0, 30, 30)
val image = ImageSpan(android, ImageSpan.ALIGN_BOTTOM)
span.setSpan(image, span.indexOf("-"), span.indexOf("-")+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
Post a Comment for "Is There Any Way To Insert An Imagespan In A Textview Without Disrupting The Text?"