Android:如何更改layer-list中的颜色

3
我有一个层列表。
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="@color/custom_color" />
        </shape>
    </item>
    <item android:top="-2dp" android:right="-2dp" android:left="-2dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                android:width="1dp"
                android:color="@android:color/white"/>
        </shape>
    </item>
</layer-list>

我希望在项目中的多个地方重用此可绘制对象,因此@color/custom_color(如上所示)在每种情况下被替换为不同的颜色。而不是创建单独的可绘制对象,应该有一种方法来实现它。有什么好主意吗?

1个回答

7

这个矩形形状的custom_color必须通过一个id来访问,比如在xml中定义android:id="@+id/shape_rectangle",所以首先需要定义它:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/shape_rectangle">
        <shape android:shape="rectangle" >
            <solid android:color="@color/custom_color" />
        </shape>
    </item>
    <item android:top="-2dp" android:right="-2dp" android:left="-2dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                android:width="1dp"
                android:color="@android:color/white"/>
        </shape>
    </item>
</layer-list>

然后:
    LayerDrawable shapeRectangle = (LayerDrawable) ContextCompat.getDrawable(context, R.drawable.custom_layer);
    GradientDrawable gradient = (GradientDrawable) shapeRectangle.findDrawableByLayerId(R.id.shape_rectangle);
    gradient.setColor(Color.RED);

custom_layer替换为你的可绘制对象名称。


1
谢谢,如果能够在XML布局中完成,或者仅从Java / Kotlin完成,那就更好了。 - hhg
1
@hhg 我不认为你可以通过 XML 实现相同的功能。 - user8959091

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接