android MenuItem setVisible ()

0

I try that if a condition is met, an item in the side menu of the app is not displayed. It does not give error, and debugging takes well the value of the item, but does not do anything. The code is as follows:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    MenuItem mVencidos = menu.findItem(R.id.miMantenimientosVencidos);
    MenuItem iVencidas = menu.findItem(R.id.miInspeccionesVencidas);

    mostarVencidosUsuario(mVencidos);
    mostarVencidosUsuario(iVencidas);

    return true;
}

private void mostarVencidosUsuario(MenuItem item){ 
   // admin es un campo que en este caso si que está a falso
    if(admin == false) {
        item.setVisible(false);
    }
}

Another option that I tried without success was this: create 2 different menus, one with all the items and the other without which I want to hide. Then load one or the other depending on whether the condition is fulfilled

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    if(admin)
        getMenuInflater().inflate(R.menu.menu_admin, menu);
    else
        getMenuInflater().inflate(R.menu.menu_no_admin, menu);

    return true;
}

I have published the solution in the answers.

    
asked by Juan 25.05.2018 в 15:02
source

1 answer

2

Thanks to the link in the answer of @ A.Cedano I managed it in the following way:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    NavigationView navigationView = findViewById(R.id.nav_view);
    if(admin){
        navigationView.getMenu().clear();
        navigationView.inflateMenu(R.menu.menu_admin);
    } else {
        navigationView.getMenu().clear();
        navigationView.inflateMenu(R.menu.menu_no_admin);
    }
    return true;
}
    
answered by 28.05.2018 / 11:50
source