[英]Android - SpannableString set Images
I have an ArrayList
of drawable resource and I want to add that icon to my string on the text start 我有一个可绘制资源的ArrayList
,我想将该图标添加到文本开头的字符串中
example this is my text 例子这是我的文字
hello world 你好,世界
now I want to add multi-image or icon at the start of text so it will be like this 现在我想在文本的开头添加多图像或图标,这样
emoji emoji emoji emoji hello world 表情符号表情符号表情符号你好世界
I just try this 我只是尝试这个
SpannableString spannableString = new SpannableString("hello world");
for(int i =0;i < resource.size(); i++){
Drawable drawable = getDrawable(context,resource.get(i),ContextCompat.getColor(context,R.color.gray));
drawable.setBounds(0, 0, 22, 22);
ImageSpan span1 = new ImageSpan(drawable);
spannableString.setSpan(span1, i, i+1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
and this the getDrawable function its only for change resource color 而此getDrawable函数仅用于更改资源颜色
private static Drawable getDrawable(Context context, int resource, int color){
Drawable outgoing = ContextCompat.getDrawable(context, resource);
ColorFilter filter = new LightingColorFilter(color, color);
outgoing.setColorFilter(filter);
return outgoing;
}
but I get an error 但我得到一个错误
java.lang.IndexOutOfBoundsException: setSpan (16 ... 17) ends beyond length 16 java.lang.IndexOutOfBoundsException:setSpan(16 ... 17)结束于长度16
its seems my code insert emoji on the string according to the start and end position but what I want its insert at the start of the text 它似乎我的代码根据开始和结束位置在字符串上插入了表情符号,但是我希望它在文本的开头插入
{emoji emoji emoji emoji} my text here {emoji emoji表情符号emoji表情符号}我的文字在这里
you can use this code , it should work for you 您可以使用此代码,它应该适合您
Drawable image =
context.getResources().getDrawable(imageResId[position]);
image.setBounds(0, 0, image.getIntrinsicWidth(),
image.getIntrinsicHeight());
SpannableString sb = new SpannableString(" ");
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Another Solution :- 另一个解决方案:
String html="";
for (int i = 0; i < emojilist.length-1; i++) {
html += "<img src ='"+ emojilist[i] +"'/>";
}
Spanned cs = Html.fromHtml(html, imageGetter, null);
textviewobject.setText(cs);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.