How can I do something, 0.5 second after text changed in my EditText?

前端 未结 14 1190
渐次进展
渐次进展 2020-12-23 08:49

I am filtering my list using an EditText. I want to filter the list 0.5 second after user has finished typing in EditText. I used the afterTextChanged

14条回答
  •  温柔的废话
    2020-12-23 09:46

    Try this

    class DelayTextWatcher(val ms: Long = 500, val textChanged: (String) -> Unit) : TextWatcher {
    
    private var timer: CountDownTimer? = null
    override fun afterTextChanged(p0: Editable) {
        timer?.cancel()
        timer = object : CountDownTimer(ms, ms) {
            override fun onTick(millisUntilFinished: Long) {
    
            }
    
            override fun onFinish() {
                textChanged(p0.toString())
            }
        }.start()
    }
    
    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }
    
    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }
    
    fun dispose() {
        timer?.cancel()
    }
    

    }

提交回复
热议问题