以编程方式设置导航视图MenuItem样式

Fhl*_*Fhl 3 android navigationview

是否可以通过编程方式在新导航视图中设置MenuItem的样式?我正在动态构建菜单,不能使用静态XML文件.我一直无法找到有关此事的任何信息.

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

更新2:在类NavigationView中有setItemTextColor(ColorStateList).据我所知,不可能设置单独的项目颜色?谢谢

Ell*_*Zou 9

如果要设置菜单图标:

第一集navigationView.setItemIconTintList(null),

NavigationView navigationView = (NavigationView) findViewById(R.id.main_nav_view);
navigationView.setItemIconTintList(null);
Run Code Online (Sandbox Code Playgroud)

并获取menuitem,为其设置图标.

MenuItem menuItem = navigationView.getMenu().getItem(0);
menuItem.setIcon(R.drawable.nav_new_drawable);
Run Code Online (Sandbox Code Playgroud)

并且还可以设置文字颜色,如下所示:

navigationView.setItemTextColor(ColorStateList textColor);
Run Code Online (Sandbox Code Playgroud)

并设置项目背景,如下所示:

navigationView.setItemBackgroundResource(int resId)
Run Code Online (Sandbox Code Playgroud)

- -编辑 - -

由于您已经了解上述内容,因此可以尝试以下代码.

<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);
Run Code Online (Sandbox Code Playgroud)