How to detect if users stop typing in EditText android

前端 未结 7 1364
长情又很酷
长情又很酷 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:16

    import android.os.Handler
    import android.text.Editable
    import android.text.TextWatcher
    
    class EndTypingWatcher(
            var delayMillis: Long = DELAY,
            val action: () -> Unit
    
    ) : Handler(), TextWatcher {
        companion object {
            private const val DELAY: Long = 1000
        }
    
        var lastEditTime: Long = 0
    
        private val finishCheckerRunnable = Runnable {
            if (System.currentTimeMillis() > lastEditTime + delayMillis - 500) {
                action.invoke()
            }
        }
    
        override fun afterTextChanged(s: Editable?) {
            afterTextChanged()
        }
    
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            onTextChanged()
        }
    
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
    
        private fun afterTextChanged() {
            lastEditTime = System.currentTimeMillis()
            postDelayed(finishCheckerRunnable, delayMillis)
        }
    
        private fun onTextChanged() {
            removeCallbacks(finishCheckerRunnable)
        }
    
    }
    

    Usage:

    private const val DELAY_AFTER_STOP_TYPING = 2000
    
    ...
    
    editText.addTextChangedListener(EndTypingWatcher(delayMillis = DELAY_AFTER_STOP_TYPING) {
        //Some end action
    })
    

提交回复
热议问题