Android: Showing Action Bar menu items depending on ViewPager

前端 未结 4 1401
深忆病人
深忆病人 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 01:50

    You can implement onCreateOptionsMenu() in your Fragment and set 'setHasOptionsMenu(true)' for the fragment

    0 讨论(0)
  • 2021-01-02 02:02

    a possible solution for this problem would be inflating your custom menu inside the activity hosts your ViewPager and getting a menu reference as below:

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         getMenuInflater().inflate(R.menu.custom_menu, menu);
         customMenu = menu;
         return super.onCreateOptionsMenu(menu);
     }
    

    after that you can easily hide/show the menu's items without any delay inside onPageSelected method as below:

     @Override
     public void onPageSelected(int position) {
      switch (position) {
            case 0: { 
               customMenu.getItem(0).setVisible(false);
               break;
            }
           case 1: { 
               customMenu.getItem(0).setVisible(true);
                 break;
            }
         }
    
    0 讨论(0)
  • 2021-01-02 02:07

    invalidateOptionsMenu make the system calls the method onPrepareOptionsMenu, so you can override this method as follows:

    public boolean onPrepareOptionsMenu(Menu menu) {
          int pageNum = getCurrentPage();
          if (pageNum == 1) {
             menu.findItem(R.id.menu_search).setVisible(true);
    
          }
          else {
             menu.findItem(R.id.menu_search).setVisible(false);
          }
       }
    
    public void onPageSelected(int pageNum) {
        invalidateOptionsMenu();
    }
    
    0 讨论(0)
  • 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().

    0 讨论(0)
提交回复
热议问题