I have an activity with 5 fragments. I am using a FragmentPageAdapter
from the support library to achieve swiping.
Fragment4 needs to have an additional menu item added to the action bar. I can get this working fine, ONLY if the user selects the tab and doesn't swipe to it. If the user swipes to the tab the additional menu item does not show all the time.
Essentially, when i swipe to Fragment3, the menu item will show (because Fragment4's onCreateView is called and stored into memory), it stays when i swipe to Fragment4 (the one intended to have the menu item) and then disappears again when i swipe to Fragment5 (which it should do). However, it stays gone unless I swipe all the back to Fragment2 and then proceed forward. The only exception being that if I am at least 2 fragments away and select the tab, then it will correctly show the menu item for Fragment4.
Also, if it is showing the menu item from Fragment3 because it is calling the onCreate at that point in execution, why does it then disappear when swiping to Fragment5? It is my understanding that the FragmentPageAdapter has 3 fragments 'loaded' at one time to enable the smooth swiping feature..
Please see code below.
public View onCreateView(){
..
setHasOptionsMenu(true);
..
return view;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
SubMenu sub = menu.addSubMenu("Options");
sub.add(0, EMAIL, 0, "Email");
sub.add(0, FILTER, 0, "Filter");
sub.add(0, SAVE, 0, "Save");
sub.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
setMenuVisibility(true);
}
if I add setMenuVisibility(true)
to onActivityCreated
the menu will show when the previous fragment comes into view because that is technically when MyFragment.onActivityCreated
is called, so then the menu is showing for the correct tab and the previous tab. However, if i swipe past the MyFragment tab the menu disappears and will not reappear when swiping back the the MyFragment tab or any other tab. The documentation about onCreateOptionsMenu
states
"This is only called once, the first time the options menu is displayed. To update the menu every time it is displayed, see onPrepareOptionsMenu(Menu)." >
So I tried adding
public void onPrepareOptionsMenu(Menu menu){
setMenuVisibility(true);
}
but it has no effect at all. I am obviously missing something here... this should work
EDIT:
Ok, so the more I look into ActionBarSherlock, the more it seems that this behavior is only available using that library. It does not appear to be part of the 'native' action bar/FragmentPagerAdapter
behavior for any version of Android. Can anyone confirm this for me?
I experienced the same issues as you did, menu icons did show on tab select but not on swipe. This solution worked for me:
Click see johanols comment.
Your other issue seems strange to me. Why not keep all 5 fragments loaded?
mViewPager.setOffscreenPageLimit(5);
Hope it helps :)