Searchview auto submit after couple of letters or seconds

痴心易碎 提交于 2019-12-25 03:58:21

问题


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?


回答1:


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
        }
    });



回答2:


Use this code, I just had the same problem and figured out how to implement it.

The code is commented and I believe it is self explanatory, otherwise feel free to ask anything!

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    MenuItem searchBackupsButton = menu.findItem(R.id.action_search);
    searchView = (SearchView) searchBackupsButton.getActionView();

    // Set menu items visible
    searchBackupsButton.setVisible(true);
    setupSearchView(searchBackupsButton);
}



private void setupSearchView(final MenuItem searchItem) 
{
    if (isAlwaysExpanded()) 
    {
        searchView.setIconifiedByDefault(false);
    } 
    else 
    {
        searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
    }

    searchView.setOnQueryTextListener(new OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query)
        {
            // If you are using a pager view (tabbed) you can get the current one here
            if(pager.getCurrentItem() == 0)
            {
                // do your searches here

                // Hide the keyboard
                searchView.clearFocus();

            }
            // same as above
            else if(pager.getCurrentItem() == 1)
            {
                // do your searches here

                // Hide the keyboard
                searchView.clearFocus();
            }
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) 
        {
            // Here for each key pressed there will be a timer starting from X and drecrementing.
            // When the timer reaches zero it will perform a search
            // So, lets say the user inserted letter 'a'. 500ms later, if the user didnt input
            // anything else the search for query 'a' will be made.
            Log.d(TAG, "Query: " + newText);

            // if there is already a count down running, cancel it and start a new one
            if(isCountDownTimerRunning)
            {
                countDownTimer.cancel();
            }

            // There is nothing to search for, show the full list!
            // This is usefull when the user presses the cross 'x' on the search view
            // Then the full list will be shown again
            // Or when the user presses backspace until it clears the searchview
            if("".equals(newText) || newText == null)
            {
                // check what current fragment is on the pager
                if(pager.getCurrentItem() == 0)
                {
                    // There is nothing to search for, show the full list!
                }
                // if cloud backups
                else if(pager.getCurrentItem() == CLOUD_BACKUPS_FRAGMENT_POSITION)
                {
                    // There is nothing to search for, show the full list!
                }
            }
            else
            {
                // Get the active fragment
                if(pager.getCurrentItem() == 0) 
                    countDownTimer = timedSearchQuery(TIME_INTERVAL_BETWEEN_KEY_PRESSED_AND_SEARCH, newText, 0);
                else if(pager.getCurrentItem() == 1)
                    countDownTimer = timedSearchQuery(TIME_INTERVAL_BETWEEN_KEY_PRESSED_AND_SEARCH, newText, 1);
            }
            return false;
        }
    });
}

    private CountDownTimer timedSearchQuery(long timeInMillis, final String searchFor, final int fragment)
{           
    countDownTimer = new CountDownTimer(timeInMillis, timeInMillis/2) { 
        @Override
        public void onTick(long millisUntilFinished) {
        }
        @Override
        public void onFinish() {
            if(fragment == 0)
                // do your search on fragment @ position zero;
            else if(fragment == 1)
                // do your search on fragment  2 position 1

                // and so on...
        }
    };

    countDownTimer.start();
    isCountDownTimerRunning = true;

    return countDownTimer;
}

protected boolean isAlwaysExpanded() {
    return false;
}


来源:https://stackoverflow.com/questions/23911317/searchview-auto-submit-after-couple-of-letters-or-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!