Can't cast SearchView in Fragment (AppCompat)

2020-07-18 04:35发布

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"
   />

1条回答
狗以群分
2楼-- · 2020-07-18 05:30

Right way to cast SearchView in AppCompat library:

MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
查看更多
登录 后发表回答