How to detect if users stop typing in EditText android

前端 未结 7 1308
长情又很酷
长情又很酷 2020-12-24 14:31

I have an EditText field in my layout. I want to perform an action when the user stops typing in that edittext field. I have implemented TextWatcher and use its functions

相关标签:
7条回答
  • 2020-12-24 15:28

    If you use Kotlin, use this extension function:

    fun TextView.afterTextChangedDelayed(afterTextChanged: (String) -> Unit) {
        this.addTextChangedListener(object : TextWatcher {
            var timer: CountDownTimer? = null
    
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
    
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
    
            override fun afterTextChanged(editable: Editable?) {
                timer?.cancel()
                timer = object : CountDownTimer(1000, 1500) {
                    override fun onTick(millisUntilFinished: Long) {}
                    override fun onFinish() { 
                        afterTextChanged.invoke(editable.toString()) 
                    }
                }.start()
            }
        })
    }
    

    Use example:

    editTextPassword.afterTextChangedDelayed {
        registerViewModel.addUserPassword(it)
    }
    
    0 讨论(0)
提交回复
热议问题