无法在Fragment中投射SearchView(AppCompat)

时间:2014-03-03 15:38:01

标签: android android-fragments searchview

我正在尝试从片段中侦听SearchView中的文本更改但在此行中失败:menu.findItem(R.id.action_search);

例外:

        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)

我的onCreateOptionsMenu(在片段中):

     @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;
        }
    });
}

菜单布局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 个答案:

答案 0 :(得分:19)

在AppCompat库中投射SearchView的正确方法:

MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);