androidandroid-fragmentsoptions-menu

Using Options Menu in a multi-Fragment Activity


I have a FragmentActivity which hosts a FragmentStatePagerAdapter. The pager contains multiple instances of the same fragment, in order that the user can swipe between the items in a list. I want to be able to provide the user with an options menu which will act only on the visible item.

For example, I have a list of images displayed in imageviews inside fragments. I want an option menu item allowing the user to set the image as their wallpaper.

At the moment when I try this, when onPrepareOptionsMenu is called, the code is called in multiple fragments (usually the current + next one). The same when an item is selected. This causes the wrong image to be set as the wallpaper.

How can I prevent the options menu triggering for more than the currently visible fragment?


Solution

  • My solution was to use the setOnPageChangeListener method of the ViewPager in order to keep track of which Fragment index was currently visible with the onPageSelected callback. You still have to get the initial index yourself, but in my case this was trivial