Home » Android » How do you set the max number of characters for an EditText in Android?

How do you set the max number of characters for an EditText in Android?

Posted by: admin November 29, 2017 Leave a comment

Questions:

How do you set the max number of characters for an Android EditText input? I see setMaxLines, setMaxEMS, but nothing for the number of characters.

Answers:

In XML you can add this line to the EditText View where 140 is the maximum number of characters:

android:maxLength="140"

Questions:
Answers:

You can use a InputFilter, that’s the way:

EditText myEditText = (EditText) findViewById(R.id.editText1);
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(10); //Filter to 10 characters
myEditText .setFilters(filters);

Questions:
Answers:

Dynamically:

editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_NUM) });

Via xml:

<EditText
    android:maxLength="@integer/max_length"

Questions:
Answers:

These might help:

Questions:
Answers:

It is working for me.

    etMsgDescription.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maximum_character)});

    etMsgDescription.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            tvCharacterLimite.setText(" "+String.valueOf(maximum_character - etMsgDescription.getText().length()));
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });