Search code examples
androidandroid-edittextemojimaxlength

how to limit max characters in edittext with emoji inputs allowed?


I have a requirement where I need to limit the number of characters entered in EditText. I know this can be easily achieved with the attribute android:maxLength for my EditText in my .xml layout file.

But my problem is my EditText should also allow users to enter emojis. Now the catch is, the length of some of the emojis is sometimes 2 or sometimes 1. So, android:maxLength=1 doesn't allow entering emojis with length = 2.

I can get the correct length of a string (with each emoji character counted as 1) with this method of Character class:

Character.codePointCount(charSequence.toString(), 0, charSequence.toString().length())

I tried using InputFilter like so:

InputFilter inputFilter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
                if (Character.codePointCount(charSequence.toString(), 0, charSequence.toString().length()) <= maxCharactersAllowed) {
                    return null;
                } else {
                    return "";
                }
            }
        };

But charSequence returned gives me weird results for plaintext and emoji text, so that the string I am using for comparison of length gives out weird results.

Can someone please help me to correctly implement restriction of the maximum number of characters for EditText accepting emoji characters as well?


Solution

  • Thanks, Joe. With your help I was able to find a solution like so:

    editText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    oldTextString = charSequence.toString();
                }
    
                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    
                }
    
                @Override
                public void afterTextChanged(Editable editable) {
                    String newTextString = editable.toString();
                    if (!oldTextString.equals(newTextString)) {
                        if (Character.codePointCount(newTextString, 0, newTextString.length()) > maxCharactersAllowed) {
                            newTextString = oldTextString;
                        }
                        editText.setText(newTextString);
                        editText.setSelection(newTextString.length());
                    }
                }
            });