Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Navigation View MenuItem style programmatically

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

like image 943
Fhl Avatar asked Dec 01 '25 05:12

Fhl


1 Answers

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);
like image 120
Ellie Zou Avatar answered Dec 03 '25 20:12

Ellie Zou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!