javaandroidsearchview

How to make SearchView lose focus and collapse when clicking elsewhere on activity


In my app, I'm making a search interface in which the SearchView collapses and expands when it loses and gains focus respectively. However, the losing focus thing is only happening in two cases:

  1. When the back button is pressed.

  2. When the home icon beside the SearchView is pressed.

I want it to lose focus (and hence collapse) if the user clicks not only on these two things, but anywhere else on the screen (e.g., any button or any blank portion of the screen without a view on it).


Solution

  • Well I found out the following solution. I used setOnTouchListener on every view that is not an instance of searchview to collapse the searchview. It worked perfect for me. Following 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 referred to.