代码之家  ›  专栏  ›  技术社区  ›  matip

MenuItem的图标颜色未更改

  •  0
  • matip  · 技术社区  · 6 年前

    我正在尝试通过代码更改菜单项的文本和图标颜色。我已经搜索了解决方案如何做到这一点,文字正在改变,但图标没有。

        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

    此外,我还要补充一点,即使我从xml文件中删除了默认色调设置为白色,图标仍然显示为白色,即使可绘制文件原来是黑色的。我不知道为什么会这样,也许这和问题有关

    1 回复  |  直到 6 年前
        1
  •  1
  •   user10053723 user10053723    6 年前
    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);
        }