Android:更改图层列表的颜色

Android:更改图层列表的颜色,android,user-interface,layer-list,Android,User Interface,Layer List,我有一个图层列表 <?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_c

我有一个图层列表

<?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(在上面的示例中)在每种情况下都会被替换为不同的颜色。应该有一种方法来实现它,而不是创建单独的可绘制图形。有什么想法吗?

这个矩形形状的
自定义颜色必须通过
id
访问,比如说
android:id=“@+id/shape\u rectangle”
,所以首先用xml定义它:

<?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>

custom_layer
替换为可绘图文件的名称

谢谢,如果可能的话,也可以使用XML布局或仅使用Java/Kotlin?@hhg不,我不认为您可以通过XML实现同样的效果。
    LayerDrawable shapeRectangle = (LayerDrawable) ContextCompat.getDrawable(context, R.drawable.custom_layer);
    GradientDrawable gradient = (GradientDrawable) shapeRectangle.findDrawableByLayerId(R.id.shape_rectangle);
    gradient.setColor(Color.RED);