3

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.

Nitesh Kumar
  • 5,370
  • 5
  • 37
  • 54

2 Answers2

1

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

});
WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
Illegal Argument
  • 10,090
  • 2
  • 44
  • 61
  • 2
    Just a minor tip: use `count >= 10`. Consider the possibility that someone paste a text into the `EditText` that is longer than 10. You still want to catch that case.. – WarrenFaith Jul 18 '14 at 10:00
  • 1
    I also edit the code to meet the requirement of setting the text to a limit of 10 if over the limit - source of idea: http://stackoverflow.com/questions/9357543/android-call-settext-within-ontextchanged – WarrenFaith Jul 18 '14 at 10:08
0

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

android:inputType="textFilter"
Marija
  • 422
  • 4
  • 12