Android: Showing Action Bar menu items depending on ViewPager

前端 未结 4 1400
深忆病人
深忆病人 2021-01-02 01:09

I am having trouble getting the following piece of code to work out. I have a viewpager with 3 fragments, and I want a search icon to only show up on one. I s

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 02:10

    I used Nermeen's answer and managed to get it without any delay.

    I don't inflate anything in onCreateOptionsMenu, but use it to get a reference to the menu:

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         customMenu = menu;
         return super.onCreateOptionsMenu(menu);
     }
    

    Then, in onPrepareOptionsMenu(), I call the viewpager getCurrentItem() (should be something like viewPager.getCurrentItem()), call invalidateOptionsMenu() and inflate whatever menu I want in that page using the customMenu reference I created in onCreateOptionsMenu().

提交回复
热议问题