I am filtering my list using an EditText control. I want to filter the list 0.5 seconds after the 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?
This example demonstrate about How to limit text length of EditText in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
android:autoText If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors.
just use the android:hint attribute in your EditText. This text shows up when the box is empty and not focused, but disappears upon selecting the EditText box. this should be the accepted answer, +1 for simplicity.
Use:
editText.addTextChangedListener( new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } private Timer timer = new Timer(); private final long DELAY = 1000; // Milliseconds @Override public void afterTextChanged(final Editable s) { timer.cancel(); timer = new Timer(); timer.schedule( new TimerTask() { @Override public void run() { // TODO: Do what you need here (refresh list). // You will probably need to use // runOnUiThread(Runnable action) for some // specific actions (e.g., manipulating views). } }, DELAY ); } } );
The trick is in canceling and rescheduling Timer
each time, when text in EditText
gets changed.
For how long to set the delay, see this post.
Better use Handler with the postDelayed() method. In the Android's implementation, Timer will create a 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 an extra cost to create a thread.
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) { // }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With