Adding SearchView in Fragment

前端 未结 7 721
误落风尘
误落风尘 2020-12-14 02:36

Trying to include a searchview in actionbar. For this, I have done the following:

Created MenuSearch.xml in the menu folder as given below:



        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 03:24

    In my fragment's onCreateOptionsMenu the code

    SearchManager searchManager =
            (SearchManager)getActivity().getSystemService(Context.SEARCH_SERVICE);
    SearchableInfo searchableInfo =
            searchManager.getSearchableInfo(getActivity().getComponentName());
    searchItem = menu.findItem(R.id.menu_search);
    SearchView searchView = (SearchView) searchItem.getActionView();
    searchView.setSearchableInfo( searchableInfo);
    

    produced following error message: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setSearchableInfo (android.app.SearchableInfo)' on a null object reference

    After i changed in menu.xml android:actionViewClass to app:actionViewClass the problem did not occur again. menu.xml :

    
    
    

提交回复
热议问题