Using a SearchView
in my application.
Is there anyway in which I can make the call to onQueryTextChange() method delayed. Like, when user type a sequence of characters, he must wait before this method gets called.
This wait should not depend on number of characters typed yet but a small pause is required before method being hit.
I want to pause because, as the user types into the search view, a request with the string will be made to server to request the matched data, and then I will populate my ListView according to suggestions.
Activity information (if required) :
Implements SearchView.OnQueryTextListener
.
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView)MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(this);
public abstract boolean onQueryTextSubmit (String query) Called when the user submits the query. This could be due to a key press on the keyboard or due to pressing a submit button. The listener can override the standard behavior by returning true to indicate that it has handled the submit request.
SearchView widget can be implemented over ToolBar/ActionBar or inside a layout. SearchView is by default collapsible and set to be iconified using setIconifiedByDefault(true) method of SearchView class. For making search field visible, SearchView uses setIconifiedByDefault(false) method.
To get text of SearchView , use searchView. getQuery() .
To delay the call to your server, use the following code in your onQueryTextChange method, the variables mQueryString and mHandler must be class variables. also check mHandler!=null
@Override
public boolean onQueryTextChange(String searchTerm) {
mQueryString = searchTerm;
mHandler.removeCallbacksAndMessages(null);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
//Put your call to the server here (with mQueryString)
}
}, 300);
return true;
}
This should help you, your class need to implement "SearchView.OnQueryTextListener" and "cntr" must be declarated in your class
This is already twinked for a regular user typing, if you want to wait more, just raise the "waitingTime".
The request should be inside the "onFinish"
private int waitingTime = 200;
private CountDownTimer cntr;
@Override
public boolean onQueryTextChange(String newText) {
if(cntr != null){
cntr.cancel();
}
cntr = new CountDownTimer(waitingTime, 500) {
public void onTick(long millisUntilFinished) {
Log.d("TIME","seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
Log.d("FINISHED","DONE");
}
};
cntr.start();
return false;
}
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