I have a ViewPager
with two Fragments
.
In the first fragment
load SearchView
in Toolbar
.
In the second fragment
I want to hide the SearchView
and appears another item on the menu.
The problem is when I try to hide the SearchView
item from the second fragment
view in onCreateOptionsMenu
always is null.
Before updating the sdk and the android.support libraries to the latest version, from version 22, these methods work correctly.
Fragment number 1:
@Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
menu.clear();
inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.menu_view_pager, menu);
final MenuItem item = (menu.findItem(R.id.action_search));
SearchView searchView = (SearchView) item.getActionView();
MenuItemCompat.setActionView(item, searchView);
MenuItemCompat.expandActionView(item);
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setIconifiedByDefault(true);
searchView.setIconified(false);
.............
.............
}
menu.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">
<item
android:id="@+id/action_search"
android:title="@string/search_action"
android:icon="@android:drawable/ic_menu_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always"
android:orderInCategory="100"
android:gravity="start"
/>
</menu>
Fragment number two
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_edit, menu);
menu.findItem(R.id.action_search).setVisible(false);
/*The top line cause NullPointerException. In debug "action_search"
item is in ActionItems, but menu items is empty.*/
menuItem = menu.findItem(R.id.action_edit);
disableButtons();
super.onCreateOptionsMenu(menu, inflater);
}
That solution there is to this problem? Thanks
I've fixed the error updating BuildTools (v.25.0.2) and AndroidSupportRepository (v.41) Also I have used this logic in onPrepareOptionsMenu:
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
toolbar.getMenu().clear(); //remove all items
toolbar.inflateMenu(R.menu.menu_edit);
menuItem = toolbar.getMenu().findItem(R.id.action_edit);
}
Before upgrade, not could inflate the menu in this method. Only running menu.clear()