2014-12-06 72 views
0

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

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和只显示图像一个主要字符串。我应该怎么做才能解决它?

+0

请乌拉圭回合后所需的图像请.. – 2014-12-06 07:00:19

+0

我只是想表明一个笑脸图像。我在上面添加了它。 – 2014-12-06 07:06:24

回答

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