18

I have a EditText , and I would like to restrict the number of characters which could be inputted in this EditText, and make this restriction programmatically, how to do it? For example, say I would like to restrict it to only allow 10 characters.

SubbaReddy PolamReddy
  • 2,083
  • 2
  • 17
  • 23
john123
  • 589
  • 3
  • 6
  • 16
  • possible duplicate of [How to programmatically set maxLength in Android TextView?](http://stackoverflow.com/questions/2461824/how-to-programmatically-set-maxlength-in-android-textview) – Pongpat Aug 19 '14 at 16:27

4 Answers4

42

You can Use InputFilter for restricting the number of characters in EditView programmatically as:

InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(10);
your_edittext.setFilters(FilterArray);

for more help you can see this tutorial for restricting number of characters in EditView:

https://web.archive.org/web/20200222150701/http://www.tutorialforandroid.com/2009/02/maxlength-in-edittext-using-codes.html

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
1

I would implement a filter:

InputFilter filter = new InputFilter() {

   @Override
   public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
      if (source.length > 10){
       //cancel the edit or whatever
      }
   }
};
EditText editText = (EditText) findViewById(R.id.rg);
editText.setFilters(new InputFilter[] {filter});
Shine
  • 3,788
  • 1
  • 36
  • 59
1
public void setEditTextMaxLength(int length) {
    InputFilter[] FilterArray = new InputFilter[1];
    FilterArray[0] = new InputFilter.LengthFilter(length);
    edt_text.setFilters(FilterArray);
}
Deepak
  • 1,669
  • 1
  • 18
  • 28
1

Try this my friend easy game easy life InputFilter[] FilterArray = new InputFilter[1]; FilterArray[0] = new InputFilter.LengthFilter(5); input.setFilters(FilterArray);

ggg
  • 21
  • 1