Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I restrict EditText to take emojis

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.

like image 669
swetabh suman Avatar asked Jan 06 '23 05:01

swetabh suman


1 Answers

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);
}
like image 163
Patrick R Avatar answered Jan 11 '23 01:01

Patrick R