How to change MenuItem icon in ActionBar programmatically? I tried to use
MenuItem menuItem = (MenuItem)findViewById(R.id.action_settings);
menuItem.setIcon(
You can't use findViewById()
on menu items in onCreate()
because the menu layout isn't inflated yet. You could create a global Menu variable and initialize it in the onCreateOptionsMenu()
and then use it in your onClick()
.
private Menu menu;
In your onCreateOptionsMenu()
this.menu = menu;
In your button's onClick()
method
menu.getItem(0).setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher));
to use in onMenuItemClick(MenuItem item)
just do invalidateOptionsMenu();
item.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_baseline_play_circle_outline_24px));
Lalith's answer is correct.
You may also try this approach:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
invalidateOptionsMenu();
}
});
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem settingsItem = menu.findItem(R.id.action_settings);
// set your desired icon here based on a flag if you like
settingsItem.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher));
return super.onPrepareOptionsMenu(menu);
}
I resolved this problem this way:
In onCreateOptionsMenu
:
this.menu = menu;
this.menu.add("calendar");
ImageView imageView = new ImageView(getActivity());
imageView.setMinimumHeight(128);
imageView.setMinimumWidth(128);
imageView.setImageDrawable(yourDrawable);
MenuItem item = this.menu.getItem(0);
item.setActionView(imageView);
in onOptionsItemSelected
:
if (item.getOrder() == 0) {
//TODO
return true;
}
Kotlin version:
toolbar.menu.findItem(R.id.notification).icon =
ContextCompat.getDrawable(requireContext(), R.drawable.ic_notification)
toolbar.menu.findItem(R.id.notification).isVisible = true
Here is how i resolved this:
1 - create a Field Variable like: private Menu mMenuItem;
2 - override the method invalidateOptionsMenu():
@Override
public void invalidateOptionsMenu() {
super.invalidateOptionsMenu();
}
3 - call the method invalidateOptionsMenu()
in your onCreate()
4 - add mMenuItem = menu
in your onCreateOptionsMenu(Menu menu)
like this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.webview_menu, menu);
mMenuItem = menu;
return super.onCreateOptionsMenu(menu);
}
5 - in the method onOptionsItemSelected(MenuItem item)
change the icon you want like this:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.R.id.action_settings:
mMenuItem.getItem(0).setIcon(R.drawable.ic_launcher); // to change the fav icon
//Toast.makeText(this, " " + mMenuItem.getItem(0).getTitle(), Toast.LENGTH_SHORT).show(); <<--- this to check if the item in the index 0 is the one you are looking for
return true;
}
return super.onOptionsItemSelected(item);
}