在多 Fragment Activity 中使用选项菜单
我有一个 FragmentActivity
,它托管一个 FragmentStatePagerAdapter
。分页器包含同一片段的多个实例,以便用户可以在列表中的项目之间滑动。我希望能够为用户提供一个选项菜单,该菜单仅作用于可见项目。
例如,我有一个在片段内的图像视图中显示的图像列表。我想要一个选项菜单项,允许用户将图像设置为壁纸。
当我尝试此操作时,当调用 onPrepareOptionsMenu
时,会在多个片段中调用代码(通常是当前片段 + 下一个片段)。选择一个项目时也是如此。这会导致将错误的图像设置为壁纸。
如何防止选项菜单触发超出当前可见片段的内容?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的解决方案是使用 ViewPager 的 setOnPageChangeListener 方法来跟踪当前在 onPageSelected 中可见的
Fragment
索引回调。您仍然需要自己获取初始索引,但对我来说这是微不足道的My solution was to use the
setOnPageChangeListener
method of theViewPager
in order to keep track of whichFragment
index was currently visible with theonPageSelected
callback. You still have to get the initial index yourself, but in my case this was trivial您可以在活动的 onOptionsItemSelected 中拦截选项菜单回调,并从那里的正确片段中显式调用该项目,返回 true 表示您已处理它。
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.
诀窍是在填充菜单之前更改每个片段上的 sethasoptions( true|false) 。这已经帮助了我
The trick is to change sethasoptions( true|false) on each fragment before populating menu. This already helped me