我试图通过代码更改我的MenuItem的文本和图标颜色。我已经搜索了解决方案如何做,文本正在改变,但图标不是。
这是我目前的代码:
public void setItemOptionColor(boolean isActive){
MenuItem menuItem = mDrawerNavigationView.getMenu().findItem(R.id.my_item);
SpannableString spannableString = new SpannableString(menuItem.getTitle());
Drawable drawable = menuItem.getIcon();
if(isActive){
spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.accent)), 0, spannableString.length(), 0);
DrawableCompat.setTint(drawable,getResources().getColor(R.color.accent));
//drawable.setColorFilter(getResources().getColor(R.color.accent), PorterDuff.Mode.SRC_ATOP);
//drawable.setTint(getResources().getColor(R.color.accent));
}
menuItem.setIcon(drawable);
menuItem.setTitle(spannableString);
}
所以现在要更改我使用DrawableCompat
的图标颜色,但也有我的另外两个尝试被注释掉了。所有这3种方法都不起作用。
此外,我将添加即使我从xml文件中删除设置默认色调为白色,即使可绘制文件最初是黑色,图标仍然显示为白色。我不知道为什么会这样,也许它与问题有某种联系
public void setItemOptionColor(boolean isActive) {
mDrawerNavigationView.setItemIconTintList(null); // add this line
MenuItem menuItem = mDrawerNavigationView.getMenu().findItem(R.id.my_item);
SpannableString spannableString = new SpannableString(menuItem.getTitle());
Drawable drawable = menuItem.getIcon();
if (isActive) {
int color = ContextCompat.getColor(getContext(), R.color.accent);
spannableString.setSpan(new ForegroundColorSpan(color), 0, spannableString.length(), 0);
DrawableCompat.setTint(drawable, getResources().getColor(R.color.accent));
}
menuItem.setIcon(drawable);
menuItem.setTitle(spannableString);
}