如何在android中实时验证EditText,同时在按钮单击之前在输入字段中输入值,就像我们在web中使用jquery一样

问题描述 投票:0回答:2

我必须在不点击按钮的情况下实时验证android中的EditText字段。

我尝试使用 requestFocus() 方法和 setErrors() 方法进行验证,但单击按钮后出现错误。那有什么办法吗?

android validation android-edittext real-time
2个回答
0
投票

尝试使用TextWatcher

尽管有 Kotlin 扩展函数,你可能可以使用这样的东西:

editText.doOnTextChanged { text, start, before, count ->  
    // Validate text
}

0
投票

要验证您可以在单击按钮之前使用的editText,您可以使用TextWatcher,它用于监听edittext的更改。请查看下面的示例:

editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                // This method is called to notify you that characters within s are about to be replaced with new text with a length of after
                // For example, you might use it to disable a button until a certain number of characters are entered.
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                // This method is called to notify you that somewhere within s, the text has been changed.
                // For example, you might use it to dynamically update a preview as the user types.
            }

            override fun afterTextChanged(s: Editable?) {
                // This method is called to notify you that somewhere within s, the text has been changed.
                // It is called to notify you that somewhere within s, the text has been changed.
                // For example, you might use it to perform validation on user input.
                textView.text = "Entered Text: ${s.toString()}"
            }
        })
© www.soinside.com 2019 - 2024. All rights reserved.