Well, I have another simpler and tidier way of doing this. If you're using search widget as an action view in the toolbar (https://developer.android.com/guide/topics/search/search-dialog#UsingSearchWidget), you might want to make the SearchView lose focus and hide the keyboard when user touches anywhere else on the screen.
Instead of iterating and setting up touch listeners on every view in the hierarchy except the SearhView, you can simply make use of this solution since the SearchView has a AutoCompleteTextView in it.
Step 1: Make the parent view(content view of your activity) clickable and focusable by adding the following attribute
android:clickable="true"
android:focusableInTouchMode="true"
Step 2: Set OnFocusChangeListener on the SearchView AutoCompleteTextView
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final MenuItem search = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) search.getActionView();
// get a reference of the AutoCompleteTextView from the searchView
AutoCompleteTextView searchSrcText = searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchSrcText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
});
return super.onCreateOptionsMenu(menu);
}
That's it! Hopefully this is useful for future readers :)