繁体   English   中英

Android-SpannableString设置图像

[英]Android - SpannableString set Images

我有一个可绘制资源的ArrayList ,我想将该图标添加到文本开头的字符串中

例子这是我的文字

你好,世界

现在我想在文本的开头添加多图像或图标,这样

表情符号表情符号表情符号你好世界

我只是尝试这个

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);

 }

而此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;
    }

但我得到一个错误

java.lang.IndexOutOfBoundsException:setSpan(16 ... 17)结束于长度16

它似乎我的代码根据开始和结束位置在字符串上插入了表情符号,但是我希望它在文本的开头插入

{emoji emoji表情符号emoji表情符号}我的文字在这里

您可以使用此代码,它应该适合您

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);

另一个解决方案:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM