Android:根据 ViewPager 显示操作栏菜单项 [英] Android: Showing Action Bar menu items depending on ViewPager

查看:31
本文介绍了Android:根据 ViewPager 显示操作栏菜单项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法运行以下代码.我有一个带有 3 个片段的 viewpager,我希望一个搜索图标只显示在一个片段上.我开始尝试通过片段添加搜索功能,但是滑动到该页面时菜单项的呈现速度很慢.我现在正在将搜索图标添加到活动中,然后根据哪个 viewpager 页面处于活动状态来隐藏或显示,但以下内容不起作用:

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 started off trying to add the search function by the fragment, but the rendering of the menu item was slow when swiping to that page. I am now on the part to add the search icon to the activity, and then just hide or show depending on which viewpager page is active, but the following is not working:

public class MyApp extends FragmentActivity implements 
   FragmentTeams.FragmentNotification,ViewPager.OnPageChangeListener, 
      OnNavigationListener{

  ...

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);

    menuSearch = menu.findItem(R.id.menu_search);
    mSearchView = new SearchView(this);
    menuSearch.setActionView(mSearchView);
    menuSearch.setVisible(false);
    return true;
}

 @Override
public void onPageSelected(int pageNum) {

if(pageNum== 1){     
    ActionBar actionBar = MyApp.this.getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);     
        menuSearch.setVisible(true);
        invalidateOptionsMenu();

}else{           
    ActionBar actionBar = MyApp.this.getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);  
        menuSearch.setVisible(false);
        invalidateOptionsMenu();
    }
}

虽然上面确实(似乎)在 onCreateOptionsMenu 处创建并隐藏了图标,但在移动到时它不会重新启用

While the above does (appear to) create and hide the icon at onCreateOptionsMenu, it is not reenabled when moving to

 pageNum ==1  

谁能告诉我为什么会发生这种情况?

Can anyone give me some insight as to why this may be happening?

推荐答案

invalidateOptionsMenu 使系统调用方法onPrepareOptionsMenu,所以你可以重写这个方法如下:

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();
}

这篇关于Android:根据 ViewPager 显示操作栏菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆