不要在Android中通过ImageSpan在TextView中显示图像

时间:2014-12-06 06:57:11

标签: android textview imagespan

我想在 TextView 中将图片显示为笑脸。我有一个获取字符串的方法,并将ImageSpans添加到CharSequence,用图形版本替换文本表情符号,如: - )enter image description here

public Spannable addSmileySpans(CharSequence text) {
    SpannableStringBuilder builder = new SpannableStringBuilder(text);

    Matcher matcher = mPattern.matcher(text);
    while (matcher.find()) {
        int resId = mSmileyToRes.get(matcher.group());
        builder.setSpan(new ImageSpan(mContext, resId),
                        matcher.start(), matcher.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    return builder;
}

然后我在我的适配器上使用它:

viewHolder.txtReceivedBody.setText(parser.addSmileySpans(message.body));

此外,这里定义了TextView elemnt:

<TextView
            android:id="@+id/txtReceivedBody"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/imgReceivedDirection"
            android:layout_marginRight="30dp"
            android:background="@drawable/selector_conversation_received"
            android:minHeight="40dp"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:paddingTop="4dp"
            android:paddingBottom="4dp"
            android:textSize="18sp"
            android:autoLink="all"
            android:gravity="right"/>

不幸的是,没有在TextView中显示图像,只显示主字符串。我该怎么做才能解决它?

1 个答案:

答案 0 :(得分:0)

  

提供你的模式

     

我的模式是[图像的id]

textview.setText(addSmileySpans(context,edit_text.getText()));

public CharSequence addSmileySpans(Context context, CharSequence msg) {
SpannableStringBuilder builder = new SpannableStringBuilder(your_recieved_message);
Pattern pattern = Pattern.compile("\\[([^\\[\\]]+)\\]");
if( pattern != null )
{
    Matcher matcher = pattern.matcher( your_recieved_message );
    int matchesSoFar = 0;
    while( matcher.find() )
    {
        CharSequence cs =matcher.group().subSequence(1, matcher.group().length()-1);
        int value = Integer.parseInt(cs.toString());
        System.out.println("pattern is::"+matcher.group().subSequence(1, matcher.group().length()-1)); 
        int start = matcher.start() - (matchesSoFar * 2);
        int end = matcher.end() - (matchesSoFar * 2);
        Drawable Smiley = context.getResources().getDrawable(value);
        Smiley.setBounds(0, 0,15,15);
        builder.setSpan(new ImageSpan(Smiley), start + 1, end - 1, 0 );
        builder.delete(start, start + 1);
        builder.delete(end - 2, end -1);
        matchesSoFar++;

    }
}
return builder;
}