How to programmatically set maxLength in Android TextView?

ID : 20208

viewed : 8

Tags : androidtextviewmaxlengthandroid

Top 5 Answer for How to programmatically set maxLength in Android TextView?

vote vote

95

Should be something like that. but never used it for textview, only edittext :

TextView tv = new TextView(this); int maxLength = 10; InputFilter[] fArray = new InputFilter[1]; fArray[0] = new InputFilter.LengthFilter(maxLength); tv.setFilters(fArray); 
vote vote

88

Try this

int maxLengthofEditText = 4;     editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLengthofEditText)}); 
vote vote

74

Easy way limit edit text character :

EditText ed=(EditText)findViewById(R.id.edittxt); ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(15)}); 
vote vote

69

For those of you using Kotlin

fun EditText.limitLength(maxLength: Int) {     filters = arrayOf(InputFilter.LengthFilter(maxLength)) } 

Then you can just use a simple editText.limitLength(10)

vote vote

50

As João Carlos said, in Kotlin use:

editText.filters += InputFilter.LengthFilter(10) 

See also https://stackoverflow.com/a/58372842/2914140 about some devices strange behaviour.

(Add android:inputType="textNoSuggestions" to your EditText.)

Top 3 video Explaining How to programmatically set maxLength in Android TextView?

Related QUESTION?