Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing SearchView in Toolbar with Fragments

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.

like image 790
Vivek Mishra Avatar asked Jan 22 '16 08:01

Vivek Mishra


People also ask

How do I get the activity toolbar in fragment?

if you are using custom toolbar or ActionBar and you want to get reference of your toolbar/action bar from Fragments then you need to first get instance of your Main Activity from Fragment's onCreateView Method like below. ImageView vRightBtn = activity. toolbar.

What is the purpose of using fragments in an activity?

Fragments introduce modularity and reusability into your activity's UI by allowing you to divide the UI into discrete chunks. Activities are an ideal place to put global elements around your app's user interface, such as a navigation drawer.

What is fragments in mobile application development?

According to the Android documentation, a fragment is a part of applications user interface that is bound to an activity. Fragments have their lifecycle and layouts or UI components. Fragments help enrich your UI design, pass data between different screens, and adapt to different device configurations.


1 Answers

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();
}
like image 101
Malek Hijazi Avatar answered Oct 20 '22 01:10

Malek Hijazi