嵌套片段变为可见时如何设置操作栏选项菜单?

时间:2015-06-25 18:03:17

标签: java android android-fragments

当特定的嵌套片段变得可见时,我需要能够清除操作栏菜单并从嵌套片段中膨胀新的菜单。

我的应用程序包含一个使用FragmentPagerAdapter的ViewPager的主要活动。这个ViewPager有4个根片段,它们只是空白的FrameLayouts(每页一个),每个片段都包含并交换嵌套片段。这些嵌套片段可以是不同的或相同的类型(想想Instagram如何在多个选项卡中显示不同的配置文件视图)。这意味着我无法在页面滑动时使用onPrepareOptionsMenu来扩充菜单,因为我不知道哪个嵌套片段位于每个页面的根片段中。另外,我已经将offScreenPageLimit设置为3,这样我就可以在根片段之间滑动而无需重新加载。这意味着我不能在嵌套片段中对菜单进行充气,因为这样就会出现所有四个嵌套的嵌套片段菜单。

理想的解决方案是能够通过在嵌套片段字面显示在屏幕上时执行的某种回调来扩充嵌套片段内的菜单,例如,当我们滑动到包含包含嵌套片段的根片段的页面时,或者我们将嵌套片段替换为页面根片段中的另一个片段。有没有人有解决我遇到的问题的设计方案?谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

The ideal solution would be able to inflate menus from within the nested fragments through some sort of callback that gets executed when the nested fragment is literally displayed on the screen.

  1. Create a menu for the fragment in the menu directory
  2. Report that this fragment has options menu have a look
  3. Then just inflate it here, and override this method and when the fragment will become visible those menu options from fragment menu will be added to activity menu options.