The following Kotlin code have dynamic delay depending on the length of the current text.
import kotlin.concurrent.scheduleeditText.addTextChangedListener(object : TextWatcher { var timer = Timer() override fun beforeTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable?) { timer.cancel() val sleep = when(s.length) { 1 -> 1000L 2,3 -> 700L 4,5 -> 500L else -> 300L } timer = Timer() timer.schedule(sleep) { if (s.isNullOrEmpty()) { // do something } } } })
NOTE: If you are using RxJava/RxBinding
, there is an interesting solution using debounce.
The following is sample Java code for SearchView
.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { private Timer timer = new Timer(); @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(final String s) { timer.cancel(); timer = new Timer(); int sleep = 350; if (s.length() == 1) sleep = 1000; else if (s.length() <= 3) sleep = 700; else if (s.length() <= 5) sleep = 500; timer.schedule(new TimerTask() { @Override public void run() { // do something } }, sleep); return true; } });