Answer the question
In order to leave comments, you need to log in
How to completely clear ActionBar/Toolbar menu items and avoid memory leaks?
I have an Activity with a fragment container. Depending on which fragment is currently in the container, I need to dynamically change the ActionBar's menu and pass the events of this menu to the current fragment. To do this, I call invalidateOptionsMenu() to get onCreateOptionsMenu() called and set up the appropriate listeners:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear(); // Пытаюсь очистить существующим методом
Fragment fragment = getSupportFragmentManager().findFragmentByTag(mCurrentFragmentTag);
if (fragment instanceof PlayersView) {
final PlayersView view = (PlayersView) fragment;
getMenuInflater().inflate(R.menu.menu_main_players, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
@Override
public boolean onClose() {
view.loadData(false);
return false;
}
});
return true;
}
return super.onCreateOptionsMenu(menu);
}
Answer the question
In order to leave comments, you need to log in
A little inconvenient, but solved as follows. Firstly, I moved the logic of the onCreateOptionsMenu method to the fragments themselves, so as not to do a bunch of checks in the Activity for which fragment is currently in the container. Secondly, in the fragments, I keep a reference to the SearchView and remove all listeners myself:
private SearchView mActionSearch;
private void disposeActions() {
if (mActionSearch != null) {
mActionSearch.setOnQueryTextListener(null);
mActionSearch.setOnCloseListener(null);
}
mActionSearch = null;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
disposeActions();
inflater.inflate(R.menu.menu_main_players, menu);
mActionSearch = (SearchView) menu.findItem(R.id.action_search).getActionView();
mActionSearch.setOnCloseListener(new SearchView.OnCloseListener() {
@Override
public boolean onClose() {
loadData(false);
return false;
}
});
// ...
}
@Override
public void onDetach() {
super.onDetach();
disposeActions();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question