Search code examples
androidlistviewwidgetsearchview

How can I get my searchable activity to launch when my search bar widget is clicked, not when I press enter?


I have a searchbar widget on top of a mapview, and what I would like is when I click that widget, a the mapview is replaced by a listview which dynamically changes the displayed items as I enter my query and keep the searchbar widget on top. Then when I press the back arrow on the search bar widget, I return to the mapview. So far, I have implemented the search bar as per the tutorial and when I press enter it launches another activity which contains my listview, but this is not what I want as the searchbar widget disappears.

My question is, is there a way to accomplish this using the searchbar widget, or should I just implement an edittext and change the fragment when the edittext is clicked?


Solution

  • I had the same problem and the way I have implemented is I have a normal search menu icon in Activity 1 and onClick it opens another ListViewActivity.

    SearchManager searchManager =
                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        final MenuItem searchItem = menu.findItem(R.id.search);
        final SearchView searchView =
                (SearchView) searchItem.getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));
    
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                // Some code here
                return false;
            }
    
            @Override
            public boolean onQueryTextChange(String s) {
                // Some code here
                return false;
            }
        });
    
        MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                // Some code here
                return true;
            }
    
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                // Some code here
                return true;
            }
        });
    
        // Get the search close button
        ImageView closeButton = (ImageView) searchView.findViewById(R.id.search_close_btn);
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Some code here
    
                EditText et = (EditText) findViewById(R.id.search_src_text);
            }
        });
    

    You can override the textview inside searchView itself so you dont have to implement custom edittext and close and back button