How to make SearchView lose focus and collapse when you click on activity somewhere else

In my application, I create a search interface in which the SearchView collapses and expands when it loses and gains focus, respectively. However, focus loss occurs in only two cases:

  • When you click the back button

  • When the home icon is clicked next to SearchView .

I want it to lose focus (and therefore collapse) if the user clicks not only on these two things, but also somewhere else on the screen (for example, any button or any blank part of the screen without viewing it).

+7
java android searchview
source share
2 answers

Ok, I found out the following solution. I used setOnTouchListener for each view that is not an instance of searchview to collapse the search query. It worked perfect for me. Below is the code.

 public void setupUI(View view) { if(!(view instanceof SearchView)) { view.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { searchMenuItem.collapseActionView(); return false; } }); } //If a layout container, iterate over children and seed recursion. if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View innerView = ((ViewGroup) view).getChildAt(i); setupUI(innerView); } } } 

This is the answer I spoke of.

+8
source share

This works for me, mOptionsMenu is stored in onCreateOptionsMenu:

 public void setupUI(View view) { //Set up touch listener for non-text box views to hide keyboard. if(!(view instanceof EditText)) { view.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { hideSoftKeyboard(MainActivity.this); if(mOptionsMenu == null) return false; MenuItem searchMenuItem = mOptionsMenu.findItem(R.id.action_search); if(searchMenuItem == null) return false; ((SearchView)searchMenuItem.getActionView()).clearFocus(); return false; } }); } //If a layout container, iterate over children and seed recursion. if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View innerView = ((ViewGroup) view).getChildAt(i); setupUI(innerView); } } } public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); } 
0
source share

All Articles