Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't cast SearchView in Fragment (AppCompat)

I'm trying to listen to text changes in my SearchView from a Fragment but it fails on this line: menu.findItem(R.id.action_search);

Exception:

        java.lang.ClassCastException: android.support.v7.internal.view.menu.MenuItemWrapperJB cannot be cast to android.support.v7.widget.SearchView
        at se.xxx.xxx.FragmentList.onCreateOptionsMenu(FragmentList.java:155)

My onCreateOptionsMenu (in Fragment):

     @Override
  public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.main, menu);
  SearchView sv = (SearchView) menu.findItem(R.id.action_search); //crashes here

    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String s) {
            adapter.getFilter().filter(s.toString());
            return false;
        }
    });
}

menu layout xml (main.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="se.xxx.xxx.MainActivity" >

<item
    app:actionViewClass="android.support.v7.widget.SearchView"
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_search"
    android:title="blabla"
    app:showAsAction="always"
   />

like image 952
Pontus Backlund Avatar asked Dec 01 '22 19:12

Pontus Backlund


1 Answers

Right way to cast SearchView in AppCompat library:

MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
like image 91
neworld Avatar answered Dec 04 '22 14:12

neworld