Android: Showing Action Bar menu items depending on ViewPager

前端 未结 4 1428
深忆病人
深忆病人 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: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;
            }
         }
    

提交回复
热议问题