2010-07-27 112 views
34

我的IM應用程序必須支持表情圖標。它們是GIF並具有文本表示,如果用戶選擇其中的一個,則在輸入框中使用它們。但是我想在發送它們之後將它們顯示爲圖像。目前,我的自定義數組適配器在一行的TextView中顯示發送的消息。在Android中顯示錶情符號

基於文本表示的出現動態顯示圖像的正確方法是什麼?我是否需要搜索表情文本,如果發現,從佈局中刪除TextView(relativeLayout最適合?),然後添加一個帶有IM開頭的TextView,一個帶有表情符號的ImageView和另一個TextView。如果同時發送更多的表情符號可能會變得混亂。

有沒有更簡單更合乎邏輯的方法?

+0

我在做類似的事情! http://stackoverflow.com/questions/16768930/implementations-of-emoji-emoticon-view-keyboard-layouts – toobsco42 2013-05-27 16:49:50

回答

38

我會嘗試使用正則表達式以<img>標記替換所有出現的每個表情符號。然後,將該HTML轉換爲SpannedStringvia Html.fromHtml()SpannedString可用於TextView調用setText()

+2

這工作,非常感謝! – Diepie 2010-07-27 11:03:10

+0

可以請你幫忙把這個「5794d5f7895fa10a8f8e1357」轉換成EMOJI ..請幫助我@CommonWare ..謝謝... – 2017-07-25 12:42:33

117

我認爲這將是更有用的建立Spannable

private static final Factory spannableFactory = Spannable.Factory 
     .getInstance(); 

private static final Map<Pattern, Integer> emoticons = new HashMap<Pattern, Integer>(); 

static { 
    addPattern(emoticons, ":)", R.drawable.emo_im_happy); 
    addPattern(emoticons, ":-)", R.drawable.emo_im_happy); 
    // ... 
} 

private static void addPattern(Map<Pattern, Integer> map, String smile, 
     int resource) { 
    map.put(Pattern.compile(Pattern.quote(smile)), resource); 
} 

public static boolean addSmiles(Context context, Spannable spannable) { 
    boolean hasChanges = false; 
    for (Entry<Pattern, Integer> entry : emoticons.entrySet()) { 
     Matcher matcher = entry.getKey().matcher(spannable); 
     while (matcher.find()) { 
      boolean set = true; 
      for (ImageSpan span : spannable.getSpans(matcher.start(), 
        matcher.end(), ImageSpan.class)) 
       if (spannable.getSpanStart(span) >= matcher.start() 
         && spannable.getSpanEnd(span) <= matcher.end()) 
        spannable.removeSpan(span); 
       else { 
        set = false; 
        break; 
       } 
      if (set) { 
       hasChanges = true; 
       spannable.setSpan(new ImageSpan(context, entry.getValue()), 
         matcher.start(), matcher.end(), 
         Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
      } 
     } 
    } 
    return hasChanges; 
} 

public static Spannable getSmiledText(Context context, CharSequence text) { 
    Spannable spannable = spannableFactory.newSpannable(text); 
    addSmiles(context, spannable); 
    return spannable; 
} 

Actualy this code based on source from native from native Html class。

編輯:更新後的版本有戲劇性的速度提升。

+0

嗨,你可以請給我一些更多的代碼,以更好地理解,謝謝你。 – amity 2011-09-09 09:08:39

+0

感謝A-IV,你的代碼非常幫助我。 – amity 2011-09-09 09:46:16

+12

+1的真棒回答。 – 2012-04-09 12:12:12