gpt4 book ai didi

android - 将字符串中的字符替换为Image,然后设置为Textview

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:45:40 26 4
gpt4 key购买 nike

This is :) and want to :) replace with :D new image.

我有这种类型的字符串,它是我从 EditTextbox 获得的。现在我想用 image1 替换所有“:)”,用 image2 替换“:D”。我想像 string.replaceall(":)",image1) 和 string.replaceall(":D",image2)。所以任何人都可以建议我如何用小代码和更好的性能来做到这一点。我已经编写了代码并且它工作也很好但是需要很多时间。

textview.setText(getSmiledText(ctx, stringvalue));
private static final HashMap<String, Integer> emoticons = new HashMap<String, Integer>();
static {
emoticons.put(":)", R.drawable.j1);
emoticons.put(":D", R.drawable.j2);}

public static Spannable getSmiledText(Context context, String s) {
int index;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(s);

for (index = 0; index < builder.length(); index++) {
for (Entry<String, Integer> entry : emoticons.entrySet()) {
int length = entry.getKey().length();
if (index + length > builder.length())
continue;
if (builder.subSequence(index, index + length).toString()
.equals(entry.getKey())) {
builder.setSpan(new ImageSpan(context, entry.getValue()),
index, index + length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
index += length - 1;
break;
}
}
}
return builder;
}

最佳答案

检查这个:

public static Spannable getSmiledText(Context context, String s) 
{
int index;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(s);

for (Entry<String, Integer> entry : EmoticonsCode.emoticons_code.entrySet())
{
try {
int length = entry.getKey().length();
for ( index = s.indexOf(entry.getKey()); index >= 0; index = s.indexOf(entry.getKey(), index + 1))
{
System.out.println(index);
builder.setSpan(new ImageSpan(context, entry.getValue()), index, index + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return builder;
}

关于android - 将字符串中的字符替换为Image,然后设置为Textview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12795101/

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