Setting Navigation View MenuItem style programmatically

六眼飞鱼酱① 提交于 2019-12-22 10:48:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!