如何隐藏选项菜单

时间:2014-03-15 10:54:31

标签: android android-optionsmenu

我打算在打开导航抽屉时隐藏选项菜单。我该怎么做呢? hide()不起作用,我已经尝试了一些变化..

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/menu_write"
          android:title="Write"
          android:showAsAction="always"
            />

</menu>


public final class OptionsMenu{
    private Menu menu;

    public void onCreateOptionsMenu(MenuInflater inflater, Menu menu) {
        inflater.inflate(R.menu.sample, menu);
        this.menu = menu;
    }

    public boolean onMenuItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            default:
                return false;
        }
    }

    public void hide(){
        menu.findItem(R.id.menu_points).setVisible(false); //Doesn't work
    }
}

3 个答案:

答案 0 :(得分:1)

试试这个......

private boolean isDrawerOpened; // Global variable

实施DrawerListener ...

drawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {

    @Override
    public void onDrawerOpened(View view) {
        isDrawerOpened = true;
        invalidateOptionsMenu();
    }

    @Override
    public void onDrawerClosed(View view) {
        isDrawerOpened = false;
        invalidateOptionsMenu();
    }
});

并在DrawerLayout ...

中验证onCreateOptionsMenu的状态
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    if (!isDrawerOpened) {
        getMenuInflater().inflate(R.menu.sample, menu);
    }
    return true;
}

答案 1 :(得分:0)

使用closeOptionsMenu()关闭选项菜单

答案 2 :(得分:0)

答案在这里Android: How to enable/disable option menu item on button click?

onPrepareOptionsMenu(Menu menu)