3 回答

TA貢獻1775條經驗 獲得超8個贊
我會嘗試使用正則表達式用<img>標簽替換每個表情符號的所有出現。然后,將該HTML轉換為SpannedString viaHtml.fromHtml()。這SpannedString可以被用在setText()呼叫TextView。

TA貢獻1796條經驗 獲得超7個贊
我認為構建會更有用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;
}
實際上,此代碼基于本機Html類的源代碼。

TA貢獻1830條經驗 獲得超9個贊
如果您使用而不是使用來獲取可繪制對象的每個外觀的克隆,則似乎不需要整個內部for循環和刪除先前的跨度。entry.getValue()
entry.getValue().getConstantState().newDrawable()
- 3 回答
- 0 關注
- 475 瀏覽
添加回答
舉報