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

前端 未结 14 1198
渐次进展
渐次进展 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条回答
  •  萌比男神i
    2020-12-23 09:45

    Better use Handler with postDelayed() method. In the android's implementation Timer will create new thread each time to run the task. Handler however has its own Looper that can be attached to whatever thread we wish, so we won't pay extra cost to create thread.

    Example

     Handler handler = new Handler(Looper.getMainLooper() /*UI thread*/);
     Runnable workRunnable;
     @Override public void afterTextChanged(Editable s) {
        handler.removeCallbacks(workRunnable);
        workRunnable = () -> doSmth(s.toString());
        handler.postDelayed(workRunnable, 500 /*delay*/);
     }
    
     private final void doSmth(String str) {
        //
     }
    

提交回复
热议问题