Shudy Shudy - 29 days ago 11
Android Question

Add Option menu on Runtime Android

My app has to show one option in Menu, depending on the permission of the user.

the item in menu is like:

<item
android:id="@+id/action_waittime"
android:visible="false"
android:orderInCategory="100"
android:title="@string/action_waittime"
app:showAsAction="never"/>


and when the activity launch, will be by default disabled. Then in oncreate() I IQ request is done:

mConnection.subscribeIQResponseFromNamespace(this, NAMESPACE);
WaitTimeIQ waitTimeIQ = new WaitTimeIQ();
//waitTimeIQ.setFrom(mConnection.getUser());
try {
waitTimeIQ.setTo(JidCreate.from("chvcomponent.chv.cat"));
} catch (XmppStringprepException e) {
e.printStackTrace();
}
waitTimeIQ.setType(IQ.Type.get);
mConnection.sendIQMessage(waitTimeIQ);


After that I'll receive the permission answer. IF the response is "granted" I have to show the option.

I do this:

public void activeOption(string autho) {
if (autho.equals("granted")) {
Menu mMenu = mToolbar.getMenu();
mMenu.getItem(R.id.action_waittime).setVisible(true);
invalidateOptionsMenu();
}
}


But, it is not refreshed and not showed.

How can I manage to make it visible?

Answer

In your activity

private Menu menu;

In onCreateOptionsMenu(Menu menu)

this.menu = menu;

and then in

public void activeOption(string autho) {   
    if (autho.equals("granted")) {
        MenuItem item = menu.findItem(R.id.action_waittime);
        item.setVisible(true);
    }
}