lubilis lubilis - 1 year ago 110
Android Question

Android EditText maxLenght counting utf-8 encoded characters

I need to set

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

Before sending
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
according UTF-8 encoded

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

Answer Source

You could use an InputFilter, something like this:

private final InputFilter filter = new InputFilter() {
    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});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download