11

CURRENT SCENARIO

My app home page consists of navigation drawer, therefore I am having views loaded as fragments. I also have search icon in toolbar. I implemented it in menu.xml. Next step I implemented SearchView for search icon by following answer on this question Implementing search in Toolbar.

This is working fine as search view shows and can also be dismissed.

PROBLEM

I can implement search query for the search view but I cannot understand how to proceed. Problem is that onCreateOptionsMenu is in Activity and all code for search view is in the Activity. What I don't understand is data that has to be searched is in Fragment that is loaded in Activity class. I will hit another webservice to get the search result but how would I inflate searched data in Fragment again. I can't understand how to proceed in this situation.

4
  • My app home page consists of navigation drawer, therefore I am having views loaded as fragments. no, DrawerLayout does not require Fragments to be used
    – pskink
    Jan 22, 2016 at 9:51
  • I think best practice is to do it this way Jan 22, 2016 at 9:58
  • who said that? where did you read it?
    – pskink
    Jan 22, 2016 at 10:00
  • We were taught this in training Jan 22, 2016 at 10:01

1 Answer 1

14

Put this in your fragment

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    setHasOptionsMenu(true);
}

And you can get the SearchView like follows

@Override
public void onPrepareOptionsMenu(Menu menu) {
    MenuItem mSearchMenuItem = menu.findItem(R.id.mi_search);
    SearchView searchView = (SearchView) mSearchMenuItem.getActionView();
}
9
  • 1
    Ho will I get text written in searchview?? Should I have to implement textChangeListener Jan 22, 2016 at 9:30
  • 2
    Implement a query text listener on the searchview as follows: searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()) Jan 22, 2016 at 9:33
  • 1
    I am getting superNotCalled error when navigate to the fragment Jan 22, 2016 at 9:36
  • 1
    return super.onPrepareOptionsMenu(menu); at the end of the onPrepareOptionsMenu Jan 22, 2016 at 9:37
  • It's a void method how it can return? Jan 22, 2016 at 9:44

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.