Adding SearchView in Fragment

前端 未结 7 637
误落风尘
误落风尘 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 :

    <menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="...">
    <item
    android:id="@+id/menu_search"
    android:title="@string/menu_search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="ifRoom">
    

    0 讨论(0)
提交回复
热议问题