Action items from Viewpager initial fragment not being displayed

You should read this (by xcolw...)

Through experimentation it seems like the root cause is invalidateOptionsMenu getting called more than one without a break on the main thread to process queued up jobs. A guess - this would matter if some critical part of menu creation was deferred via a post, leaving the action bar in a bad state until it runs.

There are a few spots this can happen that aren't obvious:

  1. calling viewPager.setCurrentItem multiple times for the same item

  2. calling viewPager.setCurrentItem in onCreate of the activity. setCurrentItem causes an option menu invalidate, which is immediately followed by the activity's option menu invalidate

Workarounds I've found for each

  1. Guard the call to viewPager.setCurrentItem

    if (viewPager.getCurrentItem() != position)
        viewPager.setCurrentItem(position);
    
  2. Defer the call to viewPager.setCurrentItem in onCreate

    public void onCreate(...) {
        ...
        view.post(new Runnable() {
            public void run() {
                // guarded viewPager.setCurrentItem
            }
        }
    }
    

After these changes options menu inside the view pager seems to work as expected. I hope someone can shed more light into this.

source http://code.google.com/p/android/issues/detail?id=29472


The simple answer is to not use menus within fragments in the ViewPager. If you do need to use menus within the fragments, what I suggest is loading the menu's through the onCreateOptionsMenu method in the parent Activity. Obviously you will need to be able to determine which menu to show.

I was able to achieve this by using class reflection. You will also need to use the invalidateOptionsMenu method each time you switch pages. You will need a OnPageChangeListener to call this when the ViewPager changes pages.