gpt4 book ai didi

java - Android - 通过 Html.fromHtml TextView 中的图像?

转载 作者:行者123 更新时间:2023-12-02 07:04:59 25 4
gpt4 key购买 nike

我想在 Android 中的 TextView 中显示图像,并认为这可以通过 Html.fromHtml() 实现。 。我发现了不同的教程,其中图像是本地资源。当我有图像的 URL 时也可以吗?如果是的话,有人能给我举个例子吗?

最佳答案

我有解决方案。将以下代码添加到您的 TextView 中添加微笑。

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

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

static {
addPattern(emoticons, ":)", R.drawable.happy);
addPattern(emoticons, ":(", R.drawable.sad);
addPattern(emoticons, ":D", R.drawable.very_happy);
// ...as many pattern you want. But make sure you have images in drawable directory
}

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

复制粘贴后,编写以下代码以在 TextView 中设置微笑。

textView.setText(getSmiledText(ActivityName.this,"Hi :) How are you...??? :D I am very :("));

关于java - Android - 通过 Html.fromHtml TextView 中的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16214767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com