2015-10-04 62 views
0

我加入的项目(使用图标)我的菜单是这样的:编程设置形状的颜色绘制

subMenu.add(user.getName()).setIcon(R.drawable.user_bg); 

user_bg绘制的布局是这样的:

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item 
     android:id="@+id/user_color"> 
     <shape 
      xmlns:android="http://schemas.android.com/apk/res/android" 
      android:shape="oval"> 
      <solid 
       android:color="#000000" 
       /> 
      <size 
       android:width="100dp" 
       android:height="100dp" 
       /> 
     </shape> 
    </item> 

    <item 
     android:drawable="@drawable/user" 
     android:adjustViewBounds="true" 
     android:scaleType="fitXY" 
     /> 

</layer-list> 

如何可以在添加新项目后以编程方式更改可绘制的颜色(#000000)?

回答

0

以编程方式创建绘图,设置其颜色,然后将其设置在菜单上。喜欢的东西:

Drawable icon = getResources().getDrawable(R.drawable.icon); 
if (icon instanceOf ShapeDrawable) { 
    icon.getPaint().setColor(getResources().getColor(R.color.some_color)); 
    subMenu.setIcon(icon); 
} 
+0

如果我有一个'for'循环,增加了多个项目的菜单,其中每个项目有它自己的独立颜色。我在'for'循环中添加了你的代码,但是它将所有项目的颜色设置为循环中最后一种颜色。 – user5403695

0
int red = 102, green = 34, blue = 100; 
drawable.setColorFilter(red,Mode.ADD); 
drawable.setColorFilter(green,Mode.ADD); 
drawable.setColorFilter(blue,Mode.ADD); 

注:这将删除色调如果有的话,你的绘制。 检查this question,以获得更多信息abot setColorFilter()方法

0

我不知道这是否是最好的方式来做到这一点,但它的工作原理。

  1. 获取到绘制

    的引用。如果你想设置你绘制的颜色,然后添加

    ​​

    或者

    如果你想在子项到在已添加项目

    后更改颜色

    LayerDrawable drawable = (LayerDrawable)subMenu.getItem().getIcon()

  2. 呼叫Drawable.Mutate()

    drawable .Mutate();

    有关说明,请参阅项目#2的this答案

  3. 创建一个颜色绘制

    ColorDrawable newColor = new ColorDrawable(Color.parseColor("#000000"));

  4. 设置/重置颜色

    drawable.setDrawableByLayerId(R.id.user_color, newColor);

  5. 重绘绘制

    drawable.invalidateSelf();