Search code examples
androidandroid-fragmentsactionbarsherlockandroid-menu

onCreateOptionsMenu hit multiples times with fragments


I have two ListFragments (A and B, which are actually SherlockListFragments) and when I put a breakpoint in the onCreateOptionsMenu in both fragments, Fragment A is hit 3 times and Fragment B is hit 2 times. In addition, I am animating one of the menu icon when an AsyncTask is running and if I select an item in Fragment A, onCreateOptionsMenu is called again and the icon double up:

enter image description here

I'm not sure why onCreateOptionsMenu is called again because I'm just calling a method in the "details" fragment:

@Override
public void onListItemClick(final ListView l, final View v, final int position, final long id)
{
    DetailsFragment fragment = (DetailsFragment)getFragmentManager().findFragmentById(R.id.fragmentDetails);

    if (fragment != null && fragment.isInLayout())
    {
        fragment.DisplayItems();
    } 
    else 
    {
        final Intent listing = new Intent(activity.getApplicationContext(), DetailsFragmentActivity.class);
        startActivity(listing);
    }
}

UPDATE:

I'm using this code to animate the menu item:

private MenuItem refreshItem;   

private void DoRefresh() 
{
    final LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final ImageView ivRefresh = (ImageView)inflater.inflate(R.layout.refresh_view, null);

    final Animation rotation = AnimationUtils.loadAnimation(activity, R.anim.refresh);
    ImageView ivRefresh.startAnimation(rotation);

    refreshItem.setActionView(ivRefresh);

    //AsyncTask is kicked off here
}

@Override
public boolean onOptionsItemSelected(final MenuItem item) 
{
    if (item.getItemId() == R.id.refresh) {
        refreshItem = item;
        this.DoRefresh();
        return true;
    } else {
        return super.onOptionsItemSelected(item);
    }
}

Solution

  • From the documentation:

    "After the system calls onCreateOptionsMenu(), it retains an instance of the Menu you populate and will not call onCreateOptionsMenu() again unless the menu is invalidated for some reason. However, you should use onCreateOptionsMenu() only to create the initial menu state and not to make changes during the activity lifecycle."

    My guess is that the menu is being invalidated by something you are doing. What does fragment.displayItems() do?