Using Options Menu in a multi-Fragment Activity
-
27-10-2019 - |
题
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?
解决方案
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
其他提示
You can intercept the options menu callback in the activity's onOptionsItemSelected, and explicitly call the item from the correct fragment there, returning true to indicate that you've handled it.
The trick is to change sethasoptions( true|false) on each fragment before populating menu. This already helped me