【发布时间】:2012-09-26 10:57:32
【问题描述】:
我从答案 Displaying emoticons in Android 中输入了这段代码,用于在 Edittext 中显示表情符号,但是当我输入大量文本时出现问题,它变得越来越慢,几乎无法输入。 这是代码:我怎样才能让它更快?
textS.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
addSmiledText(Main.this, s);
// Log.e("",s.toString());
}
});}
private static final HashMap<String, Integer> emoticons = new HashMap<String, Integer>();
static {
emoticons.put(":)", R.drawable.face_smile);
emoticons.put(":-)", R.drawable.face_smile);
emoticons.put(":(", R.drawable.face_sad);
emoticons.put(":-(", R.drawable.face_sad);
emoticons.put(":-D", R.drawable.face_smile_big);
emoticons.put(":D", R.drawable.face_smile_big);
emoticons.put(":lol:", R.drawable.face_laughing);
emoticons.put("8)", R.drawable.face_cool);
emoticons.put(";)", R.drawable.face_wink);
emoticons.put(";-)", R.drawable.face_wink);
emoticons.put(";(", R.drawable.face_crying);
...
}
public static Spannable addSmiledText(Context ch, Editable s) {
int index;
for (index = 0; index < s.length(); index++) {
for (Entry<String, Integer> entry : emoticons.entrySet()) {
int length = entry.getKey().length();
if (index + length > s.length())
continue;
if (s.subSequence(index, index + length).toString().equals(entry.getKey())) {
s.setSpan(new ImageSpan(ch, entry.getValue()), index, index + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
index += length - 1;
break;
}
}
}
return s;
}
【问题讨论】:
-
当您使用 Traceview 分析您的代码时,您发现了什么?
-
感谢您的回答。我没有使用 Traceview。你觉得我应该吗?你能提供一些链接来看看如何做到这一点吗?
-
developer.android.com/tools/debugging/debugging-tracing.html 你会发现一次扫描一个字符通过整个字符串并不是查看最后输入的字符是否以某种方式创建表情符号的非常有效的方法。
-
我知道这效率不高,但如何让它只扫描最后两个字符?例如,我插入“ab”它扫描=ab,然后我添加“c”=“abc”它只扫描bc。
-
也许你应该看看使用TransformationMethod,它似乎是为这类事情设计的?
标签: android hashmap android-edittext textwatcher spannable