我想在fragment的操作栏中使用搜索视图,我在fragment中的代码就像
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
getActivity().getMenuInflater().inflate(R.menu.menu_search, menu);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
searchView.setIconifiedByDefault(true);
super.onCreateOptionsMenu(menu, inflater);
}
menu_search
<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="com.example.sinyuk.zhihu.Search.SearchResultActivity">
<item
android:id="@+id/action_search"
android:orderInCategory="90"
android:title="@string/action_search"
android:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom"/>
和我在活动中的代码是:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
...
return true;
}
menu_main
<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=".MainActivity">
...
<item
android:id="@+id/action_settings"
android:orderInCategory="83"
android:title="@string/action_settings"
app:showAsAction="never" />
问题是我不能得到搜索视图,它原来是一个空对象。但是fragment中的菜单视图实际上是重新创建的,似乎新的menu没有传递给
MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
请帮助我:p
正如kris larson所提到的。你必须将true传递给setHasOptionsMenu();在片段的onCreate()中,像这样
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
那么你可以像这样设置你的onCreateOptionsMenu
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_search, menu);
MenuItem search = menu.findItem(R.id.action_search);
sv=(SearchView) MenuItemCompat.getActionView(search);
super.onCreateOptionsMenu(menu, inflater);
}