Nitesh Kumar
Nitesh Kumar

Reputation: 5440

Android: Limited number of characters in EditText

I want to allow user to enter only 10 characters inside the EditText. I tried two approaches.

Approach 1:

android:maxLength="10"

Approach 2:

I used InputFilter class.

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

When I am using these approaches, the cursor stops at 10 and no more characters are visible. However, it is still taking the characters I type after those 10 characters. I can see them in the suggestion area above keyboard. To explain clearly let me take an example.

Suppose I entered "abcdefghij", it works fine. Now, suppose I entered "abcdefghijklm", I can see only first 10 characters in the EditText but when press backspace it removes last character "m" instead of removing "j", the last character visible in EditText.

How can I solve this problem? I dont want to keep the extra characters in buffer also. So that when user presses backspace it should delete the 10th character.

Upvotes: 3

Views: 1865

Answers (2)

Zibi
Zibi

Reputation: 544

Your problem should be solved by adding this to your EditText:

android:inputType="textFilter"

Upvotes: 0

Illegal Argument
Illegal Argument

Reputation: 10338

You can use edittext.addTextChangedListener.

editTextLimited.addTextChangedListener(new TextWatcher() {
    /** flag to prevent loop call of onTextChanged() */
    private boolean setTextFlag = true;

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

    }

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

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // add your code here something like this
        if(count > 10){
            Toast.makeText(context,"10 chars allowed",Toast.LENGTH_LONG).show();

            // set the text to a string max length 10:
            if (setTextFlag) {
                setTextFlag = false;
                editTextLimited.setText(s.subSequence(0, 10));
            } else {
                setTextFlag = true;
            }
        }
    } 

});

Upvotes: 1

Related Questions