我想在片段的操作栏中使用搜索视图,片段中的代码就像
@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" />
问题是我无法获得搜索视图,事实证明它是一个空对象。 但片段中的菜单视图实际上是重新创建的,似乎新的菜单没有传递给
MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
所以请帮助我:P
答案 0 :(得分:0)
@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);
}