从 MenuItem returns 视图而不是 SearchView 获取 SearchView

Getting SearchView from MenuItem returns View and not SearchView

我正在尝试从 Fragment 中的工具栏获取我的 SearchView。

我正在调用 onCreateOptionsMenu 中的菜单项。

问题:searchItem.getActionView() returns "View" 而不是 "SearchView"。请参阅下面的代码

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
    inflater.inflate(R.menu.menu_search, menu);
    final MenuItem searchItem = menu.findItem(R.id.search);
    SearchView searchView = searchItem.getActionView(); // This one is red - "returns View, should return Searchview"
}

XML 菜单项 (menu_search.xml):

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item android:title="@string/search"
    android:id="@+id/search"
    android:icon="@drawable/ic_search"
    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>

试试这个:

MenuItem search = menu.findItem(R.id.search);
SearchView searchView = (SearchView) search.getActionView();