Search code examples
javaandroidsearchview

How to use search view defined in menuoptions of the MainActivity in fragments?


I am trying to use the searchview in the toolbar (menu) in multiple fragments. So, if I switch to various fragments, the searchview would apply to and search only that fragment then. After defining it in the MainActivity, how do I use it in the fragments?


Solution

  • You should keep reference to your fragments like you want. Then depending from your situation, when you typing the request or any other way, you need to make search in your fragment, like this:

    myFragment.doSearch(query)
    

    If you have a list of frargments and you need to make a call only in currently visible, you can define the isActuallyVisible variable in each fragment(on in BaseFragment if you have one) and change it like this:

    public void setMenuVisibility(final boolean visible) {
        super.setMenuVisibility(visible);
        isActuallyVisible = visible;        
    }
    

    Then you can make search like this:

    for (Fragment frag : fragmentsList) { 
        if (frag.isActuallyVisible) {
            frag.doSearch(query);
            break;
        }
    }
    

    Hope this will help you to find the correct solution