Search code examples
androidandroid-fragmentsandroid-recyclerviewsearchview

Using single SearchView in Activity, for different fragments


I'm trying to use one searchview from actitivity toolbar menu, to filter three fragments attached to it (It's a tabbed activity) at the same time and categorizing the results in the different fragments . Kind of like the way Instagram does theirs. I've tried inflating the onCreateOptionsMenu in each fragment, but this just starts a new instance of the search i.e (search icon is .istIconified(); I want the differnt tabs to show the query text of what ever was typed in it and perform the search at the same time.Can't seem to find this solution on SO, Any help or resource will be very much appreciated


Solution

  • Well it is possible.

    first of all use "setOnQueryTextListener"

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        MenuItem item = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
    
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
    
            @Override
            public boolean onQueryTextChange(String newText) {
                Log.i("well", " this worked");
                return false;
            }
        });
    }
    

    After that pass this string to currently selected fragment by calling fragment method from the activity. click here to check how to call fragment method from activity

    From fragment method you can do anything which you want to do for.