Search code examples
androidandroid-layoutsearchview

How to overlay activity content when using SearchView?


After I tap the Search icon, I want the SearchView widget to expand, and cover up the content below it. Inbox masks the current content by overlaying an opaque gray color above it. How do I do the same thing? I am using the SearchView widget.

enter image description here


Solution

  • I achieved it by simply switching to another fragment when the searchview is expanded, and switch back when it is collapsed.. The code looks something like this:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    
        getMenuInflater().inflate(R.menu.main, menu);
    
        //Setup the search widget
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        MenuItem menuItem = menu.findItem(R.id.action_search);
        SearchView mSearchView = (SearchView) menuItem.getActionView();
    
        //Not sure if you need this line for the searchView to be expandable
        mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                //Update contents of the fragment
            }
    
            @Override
            public boolean onQueryTextChange(String s) {
                //Update contents of the fragment
            }
        });
    
        MenuItemCompat.setOnActionExpandListener(menuItem,
                new MenuItemCompat.OnActionExpandListener() {
                    @Override
                    public boolean onMenuItemActionExpand(MenuItem item) {
                        //Switch to search fragment
                    }
    
                    @Override
                    public boolean onMenuItemActionCollapse(MenuItem item) {
                        //Switch back to previous fragment
                    }
                })
        ;
    
        return super.onCreateOptionsMenu(menu);
    }