2014-03-03 65 views
4

我想聽取片段的文字在我的搜索查看變化,但在這條線失敗: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" 
    /> 

+0

在片段類確保您已導入'android.support.v7.widget'包? –

+0

android.support.v7.widget.SearchView導入 –

回答

19

正道投搜索查看在程序兼容性庫:

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

忘記回答我自己的問題,但這是我做到這一點的方式 –