How to programmatically set maxLength in Android TextView?

后端 未结 11 1680
心在旅途
心在旅途 2020-11-29 17:06

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

相关标签:
11条回答
  • 2020-11-29 17:51

    best solution i found

    textView.setText(text.substring(0,10));
    
    0 讨论(0)
  • 2020-11-29 17:55

    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))
    
    0 讨论(0)
  • 2020-11-29 17:56

    Easy way limit edit text character :

    EditText ed=(EditText)findViewById(R.id.edittxt);
    ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(15)});
    
    0 讨论(0)
  • 2020-11-29 17:58

    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);
    
    0 讨论(0)
  • 2020-11-29 17:58

    I made a simple extension function for this one

    /**
     * maxLength extension function makes a filter that 
     * will constrain edits not to make the length of the text
     * greater than the specified length.
     * 
     * @param max
     */
    fun EditText.maxLength(max: Int){
        this.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(max))
    }
    

    editText?.maxLength(10)
    
    0 讨论(0)
提交回复
热议问题