How to programmatically set maxLength in Android TextView?

后端 未结 11 1762
心在旅途
心在旅途 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: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.LengthFilter(max))
    }
    

    editText?.maxLength(10)
    

提交回复
热议问题