将图标设置到菜单项 [英] Setting icons to the menu items

查看:108
本文介绍了将图标设置到菜单项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有几个菜单项的导航抽屉.我正在尝试动态更改菜单项之一的菜单图标和文本颜色.以下代码位于具有导航抽屉的活动类之一的onCreate()中:

I have a navigation drawer with several menu items. I'm trying to dynamically change the menu icon and text color of one of the menu items. Following code is in onCreate() of one of the activity classes which have the navigation drawer:

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
changeItemWiseTextProperties(navigationView.getMenu());

这是方法定义:

public void changeItemWiseTextProperties(Menu menu) {
    menu.findItem(R.id.nav_testing).
        setTitle(Html.fromHtml("<font color='#3b9ada'>Testing</font>"));

    menu.findItem(R.id.nav_testing).
        setIcon(ContextCompat.getDrawable(this,R.drawable.icon_testing_activated));
}

尽管我可以成功设置菜单项的标题名称和字体颜色,但是对菜单图标没有影响.我无法更改.为什么会这样?

Though I can set the title name and font color of the menu item successfully, but there's no effect on the menu icon. I'm unable to change that. Why is it so?

推荐答案

我检查了代码,并在日志中打印了icon.toString():menu.findItem(R.id.nav_testing).getIcon().toString()

I checked my code and printed the icon.toString() in the logs: menu.findItem(R.id.nav_testing).getIcon().toString()

以编程方式更改菜单图标前后:menu.findItem(R.id.nav_testing).getIcon()...

before and after changing the menu icon programmatically: menu.findItem(R.id.nav_testing).getIcon()...

结果?我得到两个不同的值.这意味着图标已更改.但是为什么更改没有反映在菜单中?

Results? I was getting two different values. That means the icon was getting changed. But why was the change not reflected in the menu?

原因::我有两个图标-除了颜色外,每个方面都相同.最初是icon_testing(灰色),然后将其设置为icon_testing_activated(蓝色).

Reason: I had two icons - identical in every aspect except the color. Initially it was icon_testing(grey color) and I was then setting it to icon_testing_activated(blue color).

灰色是未选定菜单项的默认颜色,而蓝色是选定菜单项的默认颜色.由于未设置我要为其设置蓝色图标(icon_testing_activated)的菜单项,因此已将其变为默认的未选择颜色-灰色.而且由于这两个图标除了颜色相同之外,我认为setIcon()方法不起作用.

Grey was the default color of the unselected menu item, while blue was the default color for a selected menu item. Since the menu item for which I was setting the blue colored icon (icon_testing_activated) was unselected, it was turned to the default unselected color - grey. And since the two icons were identical except the color, I thought setIcon() method was not working.

解决方案::我以编程方式检查了要进行颜色更改的菜单项:

Solution: I programmatically checked the menu item for which I was doing the color change:

menu.findItem(R.id.nav_testing).setChecked(true);

这篇关于将图标设置到菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆