以编程方式设置drawable中的形状颜色

问题描述 投票:0回答:4

我正在我的菜单中添加一个项目(带图标),如下所示:

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)的颜色?

android android-layout android-xml android-drawable
4个回答
0
投票

以编程方式创建drawable,设置其颜色,然后在菜单上设置它。就像是:

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

0
投票
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()方法


0
投票

我不知道这是否是最好的方法,但它确实有效。

  1. 获得对drawable的引用 如果要设置drawable的颜色,然后添加subItem LayerDrawable drawable = (LayerDrawable)getResources().getDrawable(R.drawable.user_bg); 要么 如果要在添加项目后更改颜色 LayerDrawable drawable = (LayerDrawable)subMenu.getItem().getIcon()
  2. 调用Drawable.Mutate() drawable .Mutate(); 有关解释,请参阅this答案的第2项
  3. 创建一个颜色drawable ColorDrawable newColor = new ColorDrawable(Color.parseColor("#000000"));
  4. 设置/重置颜色 drawable.setDrawableByLayerId(R.id.user_color, newColor);
  5. 重绘drawable drawable.invalidateSelf();

0
投票

请尝试以下代码:

Drawable mDrawable = getResources().getDrawable(R.drawable.circle_drawable);
mDrawable.setColorFilter(new PorterDuffColorFilter(Color.RED,  PorterDuff.Mode.SCREEN));

使用setColorFilter()函数,我们可以通过编程方式更改drawable的颜色。

我希望这个对你有用

© www.soinside.com 2019 - 2024. All rights reserved.