Is there any way to insert an ImageSpan in a TextView without disrupting the text?

为君一笑 提交于 2019-11-27 23:38:04

问题


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 imageplace Bar!");
Drawable android = context.getResources().getDrawable(R.drawable.android);
android.setBounds(0, 0, 32,32);
ImageSpan image = new ImageSpan(android, ImageSpan.ALIGN_BASELINE);
span.setSpan(image, 4, 14, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

This will replace "imageplace" with the image. Because I'm dealing with complex multi-span text and reiteration, it's a bit of a headache to insert meaningless text at each place I want the android icon. But it looks like if start and end of span are the same, the image won't be included. Is there any way around this?


回答1:


Maybe you can add an additional space to be replaced by the ImageSpan. For example,

Spannable span = new SpannableString("Foo  imageplace Bar!");
Drawable android = context.getResources().getDrawable(R.drawable.android);
android.setBounds(0, 0, 32,32);
ImageSpan image = new ImageSpan(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.




回答2:


You have to know the length of the text, the one after you want to add the image. For example..

Drawable image = ContextCompat.getDrawable(mContext, android.R.drawable.presence_offline);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
// Replace blank spaces with image icon
String myText = "myText";
int textLength = myText.length();
SpannableString sb = new SpannableString(myText + "   " + "This is another text");
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, textLength, textLength + 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


来源:https://stackoverflow.com/questions/26859800/is-there-any-way-to-insert-an-imagespan-in-a-textview-without-disrupting-the-tex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!