How to make a menu item visible on Toolbar by clicking an existing one?

Asked

Viewed 457 times

2

I have a menu on my Toolbar, it has the following actions:

  • R.id.action_editar
  • R.id.action_salvar

How can I make so that when I click the edit action, the save action button becomes visible?

This would have to be accomplished in the onOptionsItemSelected method()?
'Cause I can’t call my menu on it to set the second action as visible, there’s some way to do this?

1 answer

2


Yes, this should be done in the method onOptionsItemSelected() but first you must obtain and keep a reference to Menuitem salvage in the method onCreateOptionsMenu():

//Variável para guardar o MenuItem salvar
MenuItem actionSalvar;
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.seu_menu, menu);

    //Guarda a referência
    actionSalvar = menu.findItem(R.id.action_salvar);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();
    switch (id) {
    case R.id.action_editar:
        ...
        ...
        //Torna visível
        actionSalvar.setVisible(true);
    break;
    case R.id.action_salvar:
        ........
        ........
        //Torna invisível
        actionSalvar.setVisible(false);
    break;
    default:
    break;
    }
    return super.onOptionsItemSelected(item);
}
  • Thank you very much ramaral, it worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.