问题
I am developing an application where I want my edittext should take Name only. I have tried using android:inputType="textCapSentences" but it seems like its not working. My edittext is still taking the emojis.
So, Is there any way i can restrict any special character or emojis input in edit text in android. If anyone have idea,Please reply. Thanks in advance.
回答1:
you can use emoji filter as code below
mEditText.setFilters(new InputFilter[]{EMOJI_FILTER});
public static InputFilter EMOJI_FILTER = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
boolean keepOriginal = true;
StringBuilder sb = new StringBuilder(end - start);
for (int index = start; index < end; index++) {
int type = Character.getType(source.charAt(index));
if (type == Character.SURROGATE || type == Character.OTHER_SYMBOL) {
return "";
}
char c = source.charAt(index);
if (isCharAllowed(c))
sb.append(c);
else
keepOriginal = false;
}
if (keepOriginal)
return null;
else {
if (source instanceof Spanned) {
SpannableString sp = new SpannableString(sb);
TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
return sp;
} else {
return sb;
}
}
}
};
private static boolean isCharAllowed(char c) {
return Character.isLetterOrDigit(c) || Character.isSpaceChar(c);
}
回答2:
Well there is a trick, But I'm not sure that it could be helpful for your case. The trick is to set inputType as textEmailAddress
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress" />
Also you can take a look at this answer .
回答3:
KeyListener keyListener = new TextKeyListener(TextKeyListener.Capitalize.SENTENCES, false);
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
setInput(YOUR_EDIT_TEXT, keyListener, imm);
回答4:
Set up a TextWatcher on editText, in OnTextChanged, do the following,
String s = charSequence.toString();
Pattern p = Pattern.compile("[^A-Za-z0-9]");
Matcher m = p.matcher(s);
boolean b = m.find();
if(b == true){
//give warning to user that special character is not allowed,
//and delete or clear the last last character in charSequence .
}
来源:https://stackoverflow.com/questions/40080149/how-can-i-restrict-edittext-to-take-emojis