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

天涯浪子 提交于 2019-12-11 02:03:17

问题


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?


回答1:


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());
                }
            }
        });


来源:https://stackoverflow.com/questions/47505866/how-to-limit-max-characters-in-edittext-with-emoji-inputs-allowed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!