AppCompatActivity中使用SearchView

一、菜单配置文件

xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:res-auto="http://schemas.android.com/apk/res-auto">
    android:id="@+id/menu_item_search"
          android:title="@string/search"
          android:icon="@android:drawable/ic_menu_search"
          res-auto:showAsAction="ifRoom"
          res-auto:actionViewClass="android.support.v7.widget.SearchView"/>    
二、获取SearchView

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.fragment_photo_gallery,menu);
    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){
        MenuItem item=menu.findItem(R.id.menu_item_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);

        SearchManager manager= (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
        ComponentName name=getActivity().getComponentName();
        SearchableInfo info=manager.getSearchableInfo(name);
        searchView.setSearchableInfo(info);
    }
}

你可能感兴趣的:(menu)