Chap 27 Challenge: Collapsing Search View

There was a lot of discussion on the web re how to collapse SearchView and hide the keyboard. I ended up using:

            searchView.setQuery("", false);
            searchView.clearFocus();
            searchView.setIconified(true);

which seems a bit opaque but worked. I tried searchItem.collapseActionView(), but this didn’t appear to do anything. Is there a preferred method?

you can call onActionViewCollapsed() on your searchView to collapse searchView:

    searchView.setOnQueryTextListener( new SearchView.OnQueryTextListener(){
        @Override
        public boolean onQueryTextSubmit(String s){
            Log.d(TAG, "QueryTextSubmit: " + s);
            QueryPreferences.setStoredQuery(getActivity(),s);
            searchView.onActionViewCollapsed();
            updateItems();
            return true;
        }

1 Like

I did this:

private void hideKeyboard(Activity activity)
{
InputMethodManager imm=(InputMethodManager)activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
//Find the currently focused view, so we can grab the correct window token from it.
View view=activity.getCurrentFocus();
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view==null)
view=new View(activity);
imm.hideSoftInputFromWindow(view.getWindowToken(),0);

}

call the method providing an activity