Search code examples
androidandroid-fragmentsactionbarsherlockandroid-viewpager

Disappearing action bar buttons when swiping between fragments


I have an app with multiple tabs in an Action Bar, and each tab has a different set of option menu icons that show up in the Action Bar. Some tabs have two icons, some have none.

The problem is that when I swipe between the screens, the buttons for the individual screens may or may not show up. I.e. on a screen where there should be two icons, there will be no icons in the Action Bar!

When I click the tabs, however, the screens always show the correct icons without fail.

I have tried analyzing the problem in the debugger. I'm certain that the FragmentPagerAdapter is correctly calling setMenuVisibility(true) for the newly selected Fragment, and other Fragments are called with setMenuVisibility(false).

I can't find an exact pattern to the appearance/disappearance of buttons. I can swipe left/right between two screens that each have two different buttons. The problem will occur anywhere after 1 to 20 swipes.

The disappearance seems to be aggravated by swiping to a screen with one icon and then back to a screen with two icons.

I have tried adding calls into the Activity.invalidateOptionsMenu() but it seems to have no affect. For example, I added this call into my TabAdapter's onPageScrollStateChanged() which is called after the swipe animation is complete. I've also tried adding this into the Fragments' onResume() or after TabAdapter.onTabSelected() is finished, to no avail.

I am using ActionBarSherlock 4.1.0 (and I've substituted in the latest android-support-v4.jar because of a different issue). My Activity extends SherlockFragmentActivity and simply instantiates a ViewPager. I have overridden the FragmentPagerAdapter for the ViewPager's adapter (following the standard example on the ViewPager Android docs).

My phone is running Android 2.3.5.


Solution

  • Several workarounds for this issue are provided in ViewPager / ActionBar, Menu Items not displaying. The fix discussed in item #8 worked for me.