Search code examples
androidencodingutf-8android-edittext

Android EditText maxLenght counting UTF-8 encoded characters


I need to set maxLenght attribute to my Android EditText, considering all UTF-8 characters. If i use maxLenght xml attribute or InputFilter.LenghtFilter programmatically, the limit result is not what i need.

Before sending EditText text to my server API, i encode it using:

String encoded = URLEncoder.encode(EditText.getText(), "utf-8");

My constant limit value is 1000 and when user types some special characters as emoticons, they seem to be considered as one letter. I'd like to set maxLenght according UTF-8 encoded String.

I tried to make some logic using TextWatcher, maybe is the right approach but i didn't have success.


Solution

  • You could use an InputFilter, something like this:

    private final InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end,
            Spanned dest, int dstart, int dend) {
            try {
                String encodedDest = URLEncoder.encode(dest.toString(), "UTF-8");
                if (encodedDest.length() > 1000) {
                    return "";
                }
            } catch (UnsupportedEncodingException uee) {
                // handle this
            }
            return null;
        }
    };
    

    This will prevent the user from adding text to the EditText if its encoded length would exceed 1000 characters. (this is what you would like to achieve, if i understand correctly)

    To add this filter to your EditText:

    yourEditTextInstance.setFilters(new InputFilter[]{filter});