Question

I would like to programmatically set maxLength property of TextView as I don't want to hard code it in the layout. I can't see any set method related to maxLength.

Can anyone guide me how to achieve this?

Was it helpful?

Solution

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

OTHER TIPS

Try this

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

Easy way limit edit text character :

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

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)

For Kotlin and without resetting previous filters:

fun TextView.addFilter(filter: InputFilter) {
  filters =
      if (filters.isNullOrEmpty()) {
        arrayOf(filter)
      } else {
        filters
          .toMutableList()
          .apply {
            removeAll { it.javaClass == filter.javaClass }
            add(filter)
          }
          .toTypedArray()
      }
}

textView.addFilter(InputFilter.LengthFilter(10))
     AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Title");


                    final EditText input = new EditText(this);
                    input.setInputType(InputType.TYPE_CLASS_NUMBER);
//for Limit...                    
input.setFilters(new InputFilter[] {new InputFilter.LengthFilter(3)});
                    builder.setView(input);

best solution i found

textView.setText(text.substring(0,10));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top