How to programmatically set maxLength in Android TextView?

后端 未结 11 1679
心在旅途
心在旅途 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:35

    My solution for SWIFT 5

    editText.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(123))
    
    0 讨论(0)
  • 2020-11-29 17:39

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

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

    To keep the original input filter, you can do it this way:

    InputFilter.LengthFilter maxLengthFilter = new InputFilter.LengthFilter(100);
            InputFilter[] origin = contentEt.getFilters();
            InputFilter[] newFilters;
            if (origin != null && origin.length > 0) {
                newFilters = new InputFilter[origin.length + 1];
                System.arraycopy(origin, 0, newFilters, 0, origin.length);
                newFilters[origin.length] = maxLengthFilter;
            } else {
                newFilters = new InputFilter[]{maxLengthFilter};
            }
            contentEt.setFilters(newFilters);
    
    0 讨论(0)
  • 2020-11-29 17:43

    Try this

    int maxLengthofEditText = 4;    
    editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLengthofEditText)});
    
    0 讨论(0)
  • 2020-11-29 17:44

    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)

    0 讨论(0)
提交回复
热议问题