If I have to change the contents of my options menu I perform it during the onMenuOpened(). This allows me to check the running state at the very moment that the user is accessing the menu.
You can do something simple like I did. Just change the text to what is needed when the menu item is touched. I needed to turn the sound off and on, plus the ability to perform an action by touching it. Here is my code:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.audioOn:
audioOn = !audioOn;
if (audioOn)
item.setTitle("Audio Off");
else
item.setTitle("Audio On");
return true;
case R.id.touchOn:
touchOn = !touchOn;
if (touchOn)
item.setTitle("Touch Off");
else
item.setTitle("Touch On");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
audioOn and touchOn are booleans checked in other parts of the code. Hope this helps.
2- Define a variable for accessing menu object in class :
var menu: Menu? = null
3- initial it in onCreateOptionsMenu :
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
this.menu = menu
return true
}
4- Access the menu items inside your code or fun :
private fun initialBalanceMenuItemOnToolbar() {
var menuItemBalance = menu?.findItem(R.id.balance)
menuItemBalance?.title = Balance?.toString() ?: 0.toString()
// for change icon : menuWalletBalance?.icon
}