Felipe Caldas
Felipe Caldas

Reputation: 2503

Menu method from Fragment1 is invoked from Fragment2

I have a MainActivity that holds reference to a FragmentAdapter and a ViewPage. In this activity, I add two fragments to a List and then this list to the FragmentAdapter:

fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));       
fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));

Now, I am successfully able to slide through those two Fragments. In fact, both of them are ListFragments. In each fragment I list many items.

For each item, I can click-hold and a Menu item will appear.

The problem occuring is that on Fragment1, the public boolean onContextItemSelected(MenuItem item) is sucessfull invoked inside Fragment1 (added the breakpoint inside this fragment).

When doing the same test in Fragment2, the breakpoint from Frag1 is invoked and not from Frag2. And, obviously, data from Frag1 is shown in Frag2.

Anyone has ever seen this?

I instanciate the menu in both fragments like this:

@Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(Menu.NONE, R.id.share, Menu.NONE, getString(R.string.share));
        menu.add(Menu.NONE, R.id.delete, Menu.NONE, getString(R.string.delete_all));
    }

Regards, Felipe

Upvotes: 0

Views: 89

Answers (1)

BoredAndroidDeveloper
BoredAndroidDeveloper

Reputation: 1359

Basically whichever fragment is instantiated first will get priority. See this link for a solution using invalidateOptionsMenu. Basically the options menu will persist until you tell android that it is invalid. On older systems you could change the menu in onPrepareOptionsMenu but because the actionbar has icons from the optionsmenu you need to destroy it completely.

So when you page to a new fragment, simply invalidate the options menu. For older devices, check in onPrepareOptionsMenu to see what fragment is visible and make those options present.

Upvotes: 2

Related Questions