Gus Gus - 2 months ago 28
Android Question

Showing/Hiding menu items in viewPager fragments WITHOUT DELAY (Android)

I am aware that similar questions have been posted on this site many times before, HOWEVER, my question is not how I can show/hide menu items in different fragments. I got that down. The problem is there is a delay between swiping fragments and the new menu items showing or hiding. This delay really detracts from the interface. The changes in the action bar menu items should be immediate, amongst other reasons, to avoid clicking certain menu items in the wrong fragment.

So question is, how can i change the menu items in the actionbar immediately when the user begins swiping the fragment to go to the next?

I know it's possible because various applications already do this.
I am currently overriding the onPrepareOptionsMenu() method in every fragment and telling it which items to show and which to hide. I use supportInvalidateOptionsMenu() method to prompt the changing of the menu items, but the lag is still too long and evident.

I am open to changing the structure/technique of my changing of the menu items in the fragment in order to achieve an IMMEDIATE change in the menu times as soon as the swiping begins.

Please help. Thanks!

Gus Gus
Answer

Ok, so after looking everywhere, and finding similar posts by other people with no true answer, I have finally figured out how to invalidate the action bar menu as soon as the pages are swiped. You want to do this in an onPageChangeListener in your activity's onCreate method as below:

yourViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() 
{
    @Override
    public void onPageSelected(int position) 
    {
        //Clear action bar menu items. 
        //This prompts the onPrepareOptionsMenu which recreates the menu with
        //with the appropriate options for a given fragment as defined by you 
        supportInvalidateOptionsMenu();
    }

    @Override
    public void onPageScrollStateChanged (int arg0)
    {
        //Clear action bar menu items and display correct ones
        //This invalidates the menu options as soon as the swiping of pages begins
        supportInvalidateOptionsMenu();
    }
}

So the onPageScrollStateChanged method is what you really want whenever you want the page swiping to trigger a specified action.

Comments