以编程方式设置导航视图菜单项样式

Setting Navigation View MenuItem style programmatically

是否可以在新的导航视图中以编程方式设置 MenuItem 的样式?我正在动态构建菜单,不能使用静态 XML 文件。我一直找不到这方面的任何信息。

更新:我熟悉设置标题和图标,但不熟悉如何设置,例如设置文本的 alpha。

更新 2:在 class NavigationView 中有 setItemTextColor(ColorStateList)。据我所知,无法设置单个项目的颜色? 谢谢

如果要设置菜单图标:

第一组navigationView.setItemIconTintList(null),

NavigationView navigationView = (NavigationView) findViewById(R.id.main_nav_view);
navigationView.setItemIconTintList(null);

并获取菜单项,为其设置图标。

MenuItem menuItem = navigationView.getMenu().getItem(0);
menuItem.setIcon(R.drawable.nav_new_drawable);

并且还可以设置文字颜色,像这样:

navigationView.setItemTextColor(ColorStateList textColor);

并设置项目背景,像这样:

navigationView.setItemBackgroundResource(int resId)

---编辑---

既然你已经知道上面的内容,你可以试试下面的代码。

<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);