Android: How to recreate Action bar when fragment changed

I have an activity showing a few fragments. Activity view contains only ViewPager initialized with custom FragmentPagerAdapter. This adapter provide navigation among 3 fragments.

All seems to work fine except Action bar.

I override onCreateOptionsMenu() method in my fragments to create individual Action bar for any fragment:

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
    {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();

//fragment specific menu creation }

When I do swipe, new fragment appears, but Action bar stay the same for a few seconds. Probably after a few seconds this method are called and Action bar get changed.

This looks pretty bad when action bar are changed in a while after swipe is finished. How can I recreate action bar immediately, before swipe begin?


You can ask android to re-create the actionbar before it automatically does by calling invalidateOptionsMenu();

Do this somewhere close to the point where you change fragments to try and decrease the 'lag' between the fragment and actionbar changing.

Edit

a complete solution may look like this:

class activity extends Activity{

private void switchFragment(){

...do fragment changing stuff

activity.invalidateOptionsMenu();

}

}

class someFragment extends Fragment{

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();


    //fragment specific menu creation
}

}

whichever fragment is open during the

activity.invalidateOptionsMenu();

will then call its

 onCreateOptionsMenu

and you can do fragment specific menu creation in there


It can be done by implementing onCreateOptionsMenu and calling setHasOptionsMenu(true) in the onAttach callback in each fragment and change the actions accordingly.

To show the fragment without any actions setHasOptionsMenu(false) in it


If you are using ActionBar tabs, You would like to see this answer:

How can I change Action Bar actions dynamically?

链接地址: http://www.djcxy.com/p/63914.html

上一篇: onCreateOptionsMenu不会在片段内部调用

下一篇: Android:如何在碎片更改时重新创建操作栏