Trying to hide and show menu items on action bar

后端 未结 4 990
灰色年华
灰色年华 2021-02-05 19:26

I have looked through the questions on stack overflow and can\'t find the solution.

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuInflater i         


        
相关标签:
4条回答
  • 2021-02-05 20:08

    Its not enough to change the isDown variable. You have to call the setVisible() method every time you want to change the visibility. That method does more than just setting a boolean value, so just changing a boolean value will not do.

    After changing the isDown value to false, you need to call invalidateOptionsMenu() which will re-launch the menu by calling onPrepareOptionsMenu() again.

    Try this code for making the menu items unvisible:

    ...
    isdown = false;
    invalidateOptionsMenu();
    ...
    
    0 讨论(0)
  • 2021-02-05 20:14

    Try this in your FragmentActivity

    public boolean onPreparePanel(int featureId, View view, Menu menu) {
        if(isLeftMenuOpened()) return false;
        return super.onPreparePanel(featureId, view, menu);
    }
    

    Method FragmentActivity.onPreparePanel creates menu for all attached fragments. You must return true for the menu to be displayed; if you return false it will not be shown.

    0 讨论(0)
  • 2021-02-05 20:30

    Try this,

    private Menu menu=null;
    @Override
    public void onCreateOptionsMenu(Menu menu,MenuInflater inflater)
    {
        inflater.inflate(R.menu.note_menu, menu);
        this.menu=menu;
    super.onCreateOptionsMenu(menu,inflater);
    menu.findItem(R.id.menuChartNoteEdit).setVisible(isdown);
    menu.findItem(R.id.menuChartOpenNote).setVisible(isdown);
    }
    

    When you want to hide menu at any where, after executing onCreateOptionsMenu() then just change value for isdown and repeat this code,

    menu.findItem(R.id.menu_settings).setVisible(isdown);
    menu.findItem(R.id.menu_save).setVisible(isdown);
    
    0 讨论(0)
  • 2021-02-05 20:30

    I have a menu with two items, first: save item, second: edit item. I wanted when I came in to edit, at first "save item" had been hidden, and when I click "edit item", "save item" was shown.

    So:

    1. declare an item in public
    2. set value to it in onCreateOptionsMenu(Menu menu, MenuInflater inflater)
    3. set visibility to isHidden()
    4. then every where I wanted, set visibility to isVisible()

    Public region:

    MenuItem saveItem;
    

    onCreateOptionsMenu:

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_detail_products, menu);
        saveItem = (MenuItem) menu.findItem(R.id.action_detail_product_save);
        saveItem.setVisible(isHidden());
    }
    

    Where i want:

    saveItem.setVisible(isVisible());
    

    Finally it works as I wanted.

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