Search code examples
androidsearchview

Searchview auto submit after couple of letters or seconds


I have a android.support.v7.widget.SearchView that I use like this:

if (query == null) {
    // Associate searchable configuration with the SearchView
   SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
   SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();

   searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
       @Override
       public boolean onQueryTextSubmit(String s) {
           return false;
       }

       @Override
       public boolean onQueryTextChange(String s) {
           Log.e(TAG, "onQueryTextChange(" + s + ")");
           if (!TextUtils.isEmpty(s) && s.length() >= 2) {
               return false;
           }
           return true;
       }
   });
   searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
   searchView.setIconifiedByDefault(false);

What I want is that when the user has written 2 letters or after 2 seconds, the searchview does an auto submit of the query. Now my override methods don't do anything.

I only enter the onQueryTextChanged when I first click on the searchbar. Not after adding some text. However when I submit the query and then do it again, then I get everything in my onQueryTextChange but then again it doesn't auto submit.

Can someone help me on this?


Solution

  • Use a editText instead of the searchView and add a textWatcher similar to this:

    searchView.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
    
                // Insert your code here for submitting
    
            }
    
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
                // TODO Auto-generated method stub
            }
    
            @Override
            public void afterTextChanged(Editable s) {
    
                // TODO Auto-generated method stub
            }
        });