问题
Is it possible to set the style of a MenuItem in the new navigation view programmatically? I am building the menu dynamically and cannot use a static XML file. I've been unable to find any information on this.
UPDATE: I am familiar with setting title and icon, but not how I can e.g. set the alpha of the text.
UPDATE 2: In the class NavigationView there is setItemTextColor(ColorStateList)
. As far as I can tell it is not possible to set individual item colors?
Thanks
回答1:
If you want to set menu icon:
First set navigationView.setItemIconTintList(null)
,
NavigationView navigationView = (NavigationView) findViewById(R.id.main_nav_view);
navigationView.setItemIconTintList(null);
and get the menuitem, set icon for it.
MenuItem menuItem = navigationView.getMenu().getItem(0);
menuItem.setIcon(R.drawable.nav_new_drawable);
And also can set text color, like this:
navigationView.setItemTextColor(ColorStateList textColor);
And set item background, like this:
navigationView.setItemBackgroundResource(int resId)
---Edit---
Since you already know the above, you can try below code.
<color name="test_alpha_color">#40999999</color>
MenuItem menuItem = navigationView.getMenu().getItem(0);
SpannableString s = new SpannableString(menuItem.getTitle());
s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.test_alpha_color)), 0, s.length(), 0);
menuItem.setTitle(s);
来源:https://stackoverflow.com/questions/31913972/setting-navigation-view-menuitem-style-programmatically