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
event of TextWatcher
for this purpose. But this event rises for each character changes in EditText.
What should I do?
You can also use TextWatcher interface and create your custom class that implements it to re-use many times your CustomTextWatcher and also you can pass views or whatever you might need to its constructor:
}
Now in your activity you can use it like this:
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
How do you determine that they have finished writing? That the edittext loses focus? Then there is setOnFocusChangedListener.
Responding to latest edit in question: If you want to wait a specific time after the latest key stroke, then you have to start up a thread at the first keypress (use TextWatcher). Constantly register the time of the latest key stroke. Let the thread sleep to the the time of the latest keystroke + 0.5 seconds. If the timestamp of the latest keystroke has not been updated, do whatever you had intended.
If you want to skip textWatcher for the first time only then add following code: This will allow textWatcher make any change from the second time.
Using timer for your case is not the best solution because of creating new object everytime. According to Timer documentation(http://developer.android.com/reference/java/util/Timer.html) it's better to use ScheduledThreadPoolExecutor -
Here is better approach
that is the event while and after finish of typing ... add a textWatcher and in the onTextChanged method put :
if (charSequence.length() > 0){// your code }