我正在我的菜单中添加一个项目(带图标),如下所示:
subMenu.add(user.getName()).setIcon(R.drawable.user_bg);
user_bg
drawable布局如下所示:
<?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>
如何在添加新项目后以编程方式更改drawable(#000000
)的颜色?
以编程方式创建drawable,设置其颜色,然后在菜单上设置它。就像是:
Drawable icon = getResources().getDrawable(R.drawable.icon);
if (icon instanceOf ShapeDrawable) {
icon.getPaint().setColor(getResources().getColor(R.color.some_color));
subMenu.setIcon(icon);
}
int red = 102, green = 34, blue = 100;
drawable.setColorFilter(red,Mode.ADD);
drawable.setColorFilter(green,Mode.ADD);
drawable.setColorFilter(blue,Mode.ADD);
注意:这将删除您的drawable中的Tint(如果有的话)。检查this question,以获得更多信息abot setColorFilter()
方法
我不知道这是否是最好的方法,但它确实有效。
LayerDrawable drawable = (LayerDrawable)getResources().getDrawable(R.drawable.user_bg);
要么
如果要在添加项目后更改颜色
LayerDrawable drawable = (LayerDrawable)subMenu.getItem().getIcon()
drawable .Mutate();
有关解释,请参阅this答案的第2项ColorDrawable newColor = new ColorDrawable(Color.parseColor("#000000"));
drawable.setDrawableByLayerId(R.id.user_color, newColor);
drawable.invalidateSelf();
请尝试以下代码:
Drawable mDrawable = getResources().getDrawable(R.drawable.circle_drawable);
mDrawable.setColorFilter(new PorterDuffColorFilter(Color.RED, PorterDuff.Mode.SCREEN));
使用setColorFilter()
函数,我们可以通过编程方式更改drawable的颜色。
我希望这个对你有用