Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OptionsMenu of Nested Fragments within ViewPager

I am using ActionBarSherlock and I am trying to implement a nested fragment structure with a viewpager.

I have an activity which contains some views and a wrapper fragmet (FragmentA)

This FragmentA contains a view pager which shows FragmentA.1, FragmentA.2 ,FragmentA.3.

By Default, onCreateOptionsMenu events are not dispatched to child fragments as it is discussed here. So I am using this solution to overcome the issue.

It works great over API level 17, but for below it does not show the optionsmenu for the first fragment but when i scroll to others everything starts to work just fine. I have tried calling onCreateOptionsMenu from parent fragment but no result. It also works when i scroll back to first fragment.

Any suggestions?

Update :

More clear way of expressing the structure :

By wrapper fragment, i meant the fragment which holds the viewpager. So the structure is

ACTIVITY 
        -> WRAPPER FRAGMENT (holds viewpager and passes childfragmentmanager to adapter(FragmentPagerAdapter) as fragmentmanager) (parent is activity)
             -> CHILDFRAGMENTS(items of viewpager) (parent is wrapper fragment but viewpager manages its framelayout)

Also i have found a temp solution which is not so nice :

if(Build.VERSION.SDK_INT > 17){

            pager.setCurrentItem(1,false);

        } else {

            new android.os.Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    pager.setCurrentItem(1, true);
                }
            }, 300);


        }
like image 722
bugraoral Avatar asked Nov 06 '13 10:11

bugraoral


2 Answers

Probably you initialise your view pager before the end of the activity's creation.
This is the problem because child fragments create their options menu but then, activity invalidate all options menu.
You must initialise your pager inside onActivityCreated method of your wrapper fragment.

like image 69
bkrcinar Avatar answered Oct 12 '22 12:10

bkrcinar


Edit

if(viewPagerAdapter.getItem(view_pager.getCurrentItem()) instanceof FragmentToFind)
{
    FragmentToFind fragment = (FragmentToFind) viewPagerAdapter.getItem(view_pager.getCurrentItem());

    fragment.onCreateOptionsMenu(menu, inflater);
}
like image 21
Kevin van Mierlo Avatar answered Oct 12 '22 12:10

Kevin van Mierlo