turtleboy
turtleboy

Reputation: 7574

How to hide an optionsmenu button at runtime

In my app i have an optionsmenu. It has 2 buttons. Depending on a boolean value i would like to show/hide one of the buttons. I've got the following code but it doesn't hide the button. How can i do this?

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.menushowmoredetails, menu);
        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(displayRotaDetails.equalsIgnoreCase("false")){
            if(item.getItemId() == R.id.moredetails)
            item.setVisible(false);
            }

        switch (item.getItemId()) {

    case R.id.back:

        onBackPressed();

        return true;

    case R.id.moredetails:

Upvotes: 0

Views: 272

Answers (1)

Anis BEN NSIR
Anis BEN NSIR

Reputation: 2555

You have to use the onPrepareOptionMenu method like this:

@Override
 public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);

// add your conditions here and change 0 with the R.id.moredetails item postion.
if(displayRotaDetails.equalsIgnoreCase("false")){
menu.getItem(1).setVisible(false);
}
}

Upvotes: 1

Related Questions