核心代码
/**
* 表情过滤器
*
* @author gavin.xiong 2016/12/21
*/
public class EmojiInputFilter implements InputFilter {
private Context context;
private String[] faceImages;
private String[] faceScr;
private final String regex;
private final Pattern pattern;
private int emojiDpSize;
private ArrayMap<String, Integer> faceBook;
public EmojiInputFilter(Context context) {
this.context = context;
faceImages = context.getResources().getStringArray(R.array.emoji);
faceScr = context.getResources().getStringArray(R.array.emoji_desc);
regex = buildRegex();
pattern = Pattern.compile(regex);
faceBook = buildEmojiToRes();
float scale = Resources.getSystem().getDisplayMetrics().density;
emojiDpSize = (int) (20 * scale + 0.5f);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (end > start) source = source.subSequence(start, end);
// 新输入的字符串为空(删除剪切等)
if (TextUtils.isEmpty(source)) return null;
return source.toString().matches(".*" + regex + ".*") ? addEmojiSpans(source) : null;
}
private CharSequence addEmojiSpans(CharSequence text) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
int resId = faceBook.get(matcher.group());
Drawable dr = ContextCompat.getDrawable(context, resId);
dr.setBounds(0, 0, emojiDpSize, emojiDpSize);
builder.setSpan(new ImageSpan(dr, ImageSpan.ALIGN_BOTTOM), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return builder;
}
private String buildRegex() {
StringBuilder regex = new StringBuilder(faceScr.length * 3);
regex.append('(');
for (String s : faceScr) {
regex.append(Pattern.quote(s)).append('|');
}
regex.replace(regex.length() - 1, regex.length(), ")");
return regex.toString();
}
private ArrayMap<String, Integer> buildEmojiToRes() {
if (faceImages.length != faceScr.length) {
throw new IllegalStateException("Emoji resource ID/text mismatch");
}
ArrayMap<String, Integer> smileyToRes = new ArrayMap<>(faceScr.length);
String packageName = context.getPackageName();
for (int i = 0; i < faceScr.length; i++) {
int resId = context.getResources().getIdentifier(faceImages[i], "drawable", packageName);
smileyToRes.put(faceScr[i], resId);
}
return smileyToRes;
}
}
使用
textView.setFilters(new InputFilter[]{new EmojiInputFilter(this)});
或
editText.setFilters(new InputFilter[]{new EmojiInputFilter(this)});
网友评论