2

I'd like to limit an EditText field to 150 characters, which I can do quite easily. However, I also need to alert the user when they try to exceed that limit, either by typing (i.e. the 151st character) or by pasting more than 150 characters.

What's the best way to go about this?

XåpplI'-I0llwlg'I -
  • 21,649
  • 28
  • 102
  • 151
Serpentine
  • 25
  • 1
  • 4

4 Answers4

5

Add a TextWatcher via EditText's addTextChangedListener() method. Simply implement the appropriate method for your use case. Perhaps show an alert dialog?

EditText text = (EditText) findViewById(R.id.text);
text.addTextChangedListener(new TextWatcher()
{
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after)
    {
        if (s.length() > n)
        {
            new AlertDialog.Builder(MyActivity.this).setTitle("Character limit exceeded").setMessage("Input cannot exceed more than " + n + " characters.").setPositiveButton(android.R.string.ok, null).show();
        }
    }

    @Override
    public void afterTextChanged(Editable s)
    {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {
    }
});
XåpplI'-I0llwlg'I -
  • 21,649
  • 28
  • 102
  • 151
2

Why bother, simply set the hint attribute to something like "Max. 150 characters"

android:hint="Max. 150 characters"

enter image description here

Daniel S. Fowler
  • 1,982
  • 15
  • 12
1

It would be better to restrict the number of characters to 150 by this attribute,

http://androidblogger.blogspot.com/2009/01/numeric-edittext-and-edittext-with-max.html

android:maxLength="150"

Hope this helps

Ramesh Sangili
  • 1,633
  • 3
  • 17
  • 31
0

I had saw a lot of good solutions, but I'd like to give a what I think as more complete and user-friendly solution, which include:

1, Limit length. 2, If input more, give a callback to trigger your toast. 3, Cursor can be at middle or tail. 4, User can input by paste a string. 5, Always discard overflow input and keep origin.

here: https://stackoverflow.com/a/46922794/2468360

hyyou2010
  • 791
  • 11
  • 22