问题
I have a navigation drawer with several menu items. I'm trying to dynamically change the menu icon and text color of one of the menu items. Following code is in onCreate()
of one of the activity classes which have the navigation drawer:
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
changeItemWiseTextProperties(navigationView.getMenu());
And here's the method definition:
public void changeItemWiseTextProperties(Menu menu) {
menu.findItem(R.id.nav_testing).
setTitle(Html.fromHtml("<font color='#3b9ada'>Testing</font>"));
menu.findItem(R.id.nav_testing).
setIcon(ContextCompat.getDrawable(this,R.drawable.icon_testing_activated));
}
Though I can set the title name and font color of the menu item successfully, but there's no effect on the menu icon. I'm unable to change that. Why is it so?
回答1:
I checked my code and printed the icon.toString() in the logs: menu.findItem(R.id.nav_testing).getIcon().toString()
before and after changing the menu icon programmatically: menu.findItem(R.id.nav_testing).getIcon()...
Results? I was getting two different values. That means the icon was getting changed. But why was the change not reflected in the menu?
Reason: I had two icons - identical in every aspect except the color. Initially it was icon_testing
(grey color) and I was then setting it to icon_testing_activated
(blue color).
Grey was the default color of the unselected menu item, while blue was the default color for a selected menu item. Since the menu item for which I was setting the blue colored icon (icon_testing_activated
) was unselected, it was turned to the default unselected color - grey. And since the two icons were identical except the color, I thought setIcon() method was not working.
Solution: I programmatically checked the menu item for which I was doing the color change:
menu.findItem(R.id.nav_testing).setChecked(true);
来源:https://stackoverflow.com/questions/36716450/setting-icons-to-the-menu-items