android - Using onPrepareOptionsMenu instead of onCreateOptionsMenu in Fragment -
i had problem setting fragment menu items in actionbar
, found way solve it, don't understand why worked.
i wanted change visibility in menu item right after inflated menu xml file in oncreateoptionsmenu
method. code seems work fine, there's no visible effect. solved problem inflating menu in oncreateoptionsmenu
method changing visibility of in onprepareoptionsmenu
method.
what want know why changing visibility in oncreateoptionsmenu
not work.
what can in onprepareoptionsmenu
can't in oncreateoptionsmenu
?
is there pattern follow here?
thanks!
here's relevant code, in case:
public class myfragment extends fragment { @override public void oncreateoptionsmenu(menu menu, menuinflater inflater) { super.oncreateoptionsmenu(menu, inflater); inflater.inflate(r.menu.my_menu, menu); // not work, compiles , runs fine, has no visible effect menuitem somemenuitem = menu.finditem(r.id.some_menu_item); somemenuitem.setvisible(false); } @override public void onprepareoptionsmenu(menu menu) { super.onprepareoptionsmenu(menu); // work menuitem somemenuitem = menu.finditem(r.id.some_menu_item); somemenuitem.setvisible(false); } }
you should call super.oncreateoptionsmenu(menu, inflater);
after have created menu, not before. sends menu in hierarchy , other fragments or activity may want add items themselves.
the activity responsible displaying , managing menu, if change visibility after has been sent activity, nothing going happen.
now, when call super.onprepareoptionsmenu(menu);
"prepare" it's menu, take changes you've made in oncreateoptionsmenu
account.
Comments
Post a Comment