用图像替换spannable中的URL

时间:2013-02-05 16:02:55

标签: android image replace textview spannable

是否有可能用图像替换spannable中的url(例如http://www.google.de)?

我有一个用图像替换所有表情符号(例如:))的函数。这个函数看起来像这样:

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_mod_im_happy);
addPattern(emoticons, ":-)", R.drawable.emo_mod_im_happy);
addPattern(emoticons, ";-)", R.drawable.emo_im_winking);
addPattern(emoticons, ";)", R.drawable.emo_im_winking);
addPattern(emoticons, "&lt;3", R.drawable.heart);
addPattern(emoticons, "<3", R.drawable.heart);
addPattern(emoticons, ":D", R.drawable.emo_im_laughing);
addPattern(emoticons, ":(", R.drawable.emo_im_sad);
addPattern(emoticons, ":-(", R.drawable.emo_im_sad);
// ...
}

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

问题是:

如果我以前称之为maintext.setAutoLinkMask(Linkify.ALL);

,我无法将TextView应用于我的主文Spannable text = getSmiledText(context,text);

有没有办法在spannable函数中用my image替换链接?

0 个答案:

没有答案