How to add Search View on Action bar on one of the

2019-09-21 05:17发布

问题:

Please provide me a better solution if you have I am working on android app in which on home Activity by using TabLaout&ViewPager i have added 5 tabs on below

  1. Home
  2. Social
  3. Notice
  4. Search
  5. Links

I have set for MainActivity in values/style but i have placed custom action bar tag in search.xml. I know how to add SearchView on action bar in activity but i am facing issues using fragments. My goal is just to show search view widget on action bar when user will on "Search" tab. On other tabs i don't want to show. Further more I have added <meta-data android:name="android.app.searchable" android:resource="@xml/searchable"/> in Manifest file in tag and setHasOptionsMenu(true); in Search Fragment. But action bar is showing on search screen without search View Widget, please correct me where i am doing wrong.

回答1:

You have to add the SearchView only in the searchFragment:

searchFragment class:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news, container, false);
...        
  setHasOptionsMenu(true);
..... 
return rootView ;}
 @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_search, menu);
        try {
            // Associate searchable configuration with the SearchView
            SearchManager searchManager =
                    (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
            SearchView searchView =
                    (SearchView) menu.findItem(R.id.action_search).getActionView();
            searchView.setSearchableInfo(
                    searchManager.getSearchableInfo(getActivity().getComponentName()));
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String s) {
                   // do your search
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String s) {
           // do your search on change or save the last string or... 
                    return false;
                }
            });


        }catch(Exception e){e.printStackTrace();}
    }

menu_search xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/action_search"
        android:icon="@drawable/action_search_btn"
        android:title="Search"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>