所以为了防止用户胡乱输入表情、同时限制用户只能输入应用自带的表情。编写了一个自定义控件来禁止输入的表情。
代码如下:
- package com.qd.widget;
- import android.content.Context;
- import android.text.InputFilter;
- import android.text.SpannableString;
- import android.text.Spanned;
- import android.text.TextUtils;
- import android.util.AttributeSet;
- import android.widget.EditText;
- /**
- * 过滤搜狗输入法或其他输入法 当中的图片或其他非法字符
- *
- * 暂时仅过滤了部分常用的表情字符
- *
- * @author QD
- *
- */
- public class MyEditText extends EditText {
- int maxLength = –1;
- public MyEditText(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- addListener(attrs);
- }
- public MyEditText(Context context, AttributeSet attrs) {
- super(context, attrs);
- addListener(attrs);
- }
- public MyEditText(Context context) {
- super(context);
- addListener(null);
- }
- private void addListener(AttributeSet attrs) {
- if (attrs != null)
- maxLength = attrs.getAttributeIntValue(“http://schemas.android.com/apk/res/android”, “maxLength”, –1);
- // 过滤输入法表情
- InputFilter filter = new InputFilter() {
- @Override
- public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
- StringBuffer buffer = new StringBuffer();
- for (int i = start; i < end; i++) {
- char c = source.charAt(i);
- // 第一个字符为以下时,过滤掉
- if (c == 55356 || c == 55357 || c == 10060 || c == 9749 || c == 9917 || c == 10067 || c == 10024
- || c == 11088 || c == 9889 || c == 9729 || c == 11093 || c == 9924) {
- i++;
- continue;
- } else {
- buffer.append(c);
- }
- }
- if (source instanceof Spanned) {
- SpannableString sp = new SpannableString(buffer);
- TextUtils.copySpansFrom((Spanned) source, start, end, null, sp, 0);
- return sp;
- } else {
- return buffer;
- }
- }
- };
- // 输入框长度限制
- if (maxLength > 0)
- setFilters(new InputFilter[] { filter, new InputFilter.LengthFilter(maxLength) });
- else
- setFilters(new InputFilter[] { filter });
- }
- }
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/app/5810.html