如何在导航抽屉打开时隐藏片段中的操作栏按钮

时间:2015-07-20 08:35:45

标签: android android-fragments navigation-drawer

我使用导航抽屉,其中一个片段我有不同的菜单。对于导航抽屉打开时的片段,如何隐藏操作栏的按钮? 例如,在图片(http://prntscr.com/7ur712)上,它是按钮REFRESH。

@Override public void onCreate(Bundle savedInstanceState) {   
super.onCreate(savedInstanceState); 
**setHasOptionsMenu(true);** }

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
**inflater.inflate(R.menu.my_menu, menu);**
}

2 个答案:

答案 0 :(得分:1)

实施 ActionBarDrawerToogle 以获取导航抽屉的状态。调用invalidateOptionsMenu();使导航抽屉的打开/关闭状态下的菜单无效。

稍后根据状态,您可以使用以下方式显示/隐藏导航项目:

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // inflate menu from xml
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.settings, menu);

    if (mState == MENU_HIDDEN)
    {
        for (int i = 0; i < menu.size(); i++)
            menu.getItem(i).setVisible(false);
    }
}

答案 1 :(得分:0)

更新actionBar按钮的最佳方法是在invalidateOptionsMenu()打开/关闭时调用NavigationDrawer

根据Android培训文档页面,当您创建ActionBarDrawerToggle时,您应该覆盖onDrawerClosedonDrawerOpened方法:

mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) { 

            /** Called when a drawer has settled in a completely closed state. */ 
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            } 

            /** Called when a drawer has settled in a completely open state. */ 
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            } 
        }; 

此外,在您的onPrepareOptionsMenu方法中,您可以检测抽屉是否打开,并加载与抽屉状态相对应的菜单:

/* Called whenever we call invalidateOptionsMenu() */ 
    @Override 
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view 
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    } 

有关详细信息,请在此处查看Android开发者文档:https://developer.android.com/training/implementing-navigation/nav-drawer.html (参见:收听开放和关闭事件)