Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set max length for EditText

I want to set a 1 character length in EditText but just in one part of condition. There is a way to set max length via XML but this will be applied for the whole condition. How to set max length programmatically?

like image 479
omar wael Avatar asked Sep 07 '16 01:09

omar wael


4 Answers

public void setEditTextMaxLength(EditText editText, int length) {
      InputFilter[] FilterArray = new InputFilter[1];
      FilterArray[0] = new InputFilter.LengthFilter(length);
      editText.setFilters(FilterArray);
  }
like image 125
Sangram Haladkar Avatar answered Oct 17 '22 13:10

Sangram Haladkar


You can add this in your XML:

android:maxLength="10"

or programmatically:

EditText editText = new EditText(this);
int maxLength = 3;    
editText.setFilters(new InputFilter[] {
    new InputFilter.LengthFilter(maxLength)
});
like image 21
Omar Vodiak Avatar answered Oct 17 '22 12:10

Omar Vodiak


In Kotlin, this extension function is handy:

fun EditText.setMaxLength(maxLength: Int) {
    filters = arrayOf(InputFilter.LengthFilter(maxLength))
}
like image 3
David Vávra Avatar answered Oct 17 '22 12:10

David Vávra


edtTime.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(4) });
like image 1
Criss Avatar answered Oct 17 '22 12:10

Criss