What's the best way to limit text length of EditText in Android

后端 未结 22 2109
囚心锁ツ
囚心锁ツ 2020-11-22 13:33

What\'s the best way to limit the text length of an EditText in Android?

Is there a way to do this via xml?

22条回答
  •  旧时难觅i
    2020-11-22 14:25

    Kotlin:

    edit_text.filters += InputFilter.LengthFilter(10)
    

    ZTE Blade A520 has strange effect. When you type more than 10 symbols (for instance, 15), EditText shows first 10, but other 5 are not visible and not accessible. But when you delete symbols with Backspace, it first deletes right 5 symbols and then removes remaining 10. To overcome this behaviour use a solution:

    android:inputType="textNoSuggestions|textVisiblePassword"
    android:maxLength="10"
    

    or this:

    android:inputType="textNoSuggestions"
    

    or this, if you want to have suggestions:

    private class EditTextWatcher(private val view: EditText) : TextWatcher {
        private var position = 0
        private var oldText = ""
    
        override fun afterTextChanged(s: Editable?) = Unit
    
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            oldText = s?.toString() ?: ""
            position = view.selectionStart
        }
    
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            val newText = s?.toString() ?: ""
            if (newText.length > 10) {
                with(view) {
                    setText(oldText)
                    position = if (start > 0 && count > 2) {
                        // Text paste in nonempty field.
                        start
                    } else {
                        if (position in 1..10 + 1) {
                            // Symbol paste in the beginning or middle of the field.
                            position - 1
                        } else {
                            if (start > 0) {
                                // Adding symbol to the end of the field.
                                start - 1
                            } else {
                                // Text paste in the empty field.
                                0
                            }
                        }
                    }
                    setSelection(position)
                }
            }
        }
    }
    
    // Usage:
    editTextWatcher = EditTextWatcher(view.edit_text)
    view.edit_text.addTextChangedListener(editTextWatcher)
    

提交回复
热议问题