Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to hide and show menu items on action bar

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

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.themenu, menu);
    MenuItem   item = menu.findItem(R.id.menu_settings);
    MenuItem item2 = menu.findItem(R.id.menu_save);
    item.setVisible(isdown);
    item2.setVisible(isdown);
    return true;
}

This sets my menu items to visible (item1 and item2). the onclick works fine

public void inflateTextarea() {
    if(isdown == true) {
        isdown = false;
        LinearLayout tl = (LinearLayout)findViewById(R.id.content);
        tl.setVisibility(View.VISIBLE);
        ScaleAnimation scale =  new ScaleAnimation(1, 1, 0, 1);
        scale.setFillAfter(true);
        scale.setDuration(500);
        tl.startAnimation(scale);
    }
}

Then this sets my isdown boolean to false. on stack people say that the onPrepareOptionsMenu should fire everytime I click but this is not the case. I am able to hide one menu item on the onclick function

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.menu_settings: 
            Log.v("Log:","edit_item pressed");
            return true;
    }
}

But I have multiple menu items that I need to hide and others that I want to show. how can I go about this?

like image 592
Dnaso Avatar asked Apr 19 '13 22:04

Dnaso


2 Answers

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();
...
like image 187
tbkn23 Avatar answered Sep 23 '22 03:09

tbkn23


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);
like image 32
Sino Raj Avatar answered Sep 24 '22 03:09

Sino Raj