Implementing SearchView in Toolbar with Fragments

人走茶凉 提交于 2019-12-04 10:40:00

问题


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.


回答1:


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();
}


来源:https://stackoverflow.com/questions/34942492/implementing-searchview-in-toolbar-with-fragments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!