I have a layer list like this:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="@color/black" />
</shape>
</item>
<item
android:drawable="@drawable/ic_pin"
android:adjustViewBounds="true"
android:scaleType="fitXY" />
</layer-list>
How can I programmatically change the color of the shape as well as the drawable?
For example, how can I change the color to #FF0000
and change the drawable to @drawable/ic_globe
programmatically?
Tint color means when we want to change the color of the image while rendering in ImageView. In XML is very easy to change tint color by just setting up the attribute android:tint="" in the ImageView tag, as shown in the following example.
Please Add id
attribute to item of layer like below code:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/bg_layer">
<shape android:shape="oval">
<solid android:color="#000000" />
</shape>
</item>
<item
android:id="@+id/top_layer"
android:drawable="@drawable/ic_pin"
android:adjustViewBounds="true"
android:scaleType="fitXY" />
</layer-list>
Code in Java
LayerDrawable bgDrawable = (LayerDrawable) getResources().getDrawable(R.drawable.border);/*drawable*/
GradientDrawable bg_layer = (GradientDrawable)bgDrawable.findDrawableByLayerId (R.id.bg_layer);/*findDrawableByLayerId*/
bg_layer.setColor(Color.RED);/*set color to layer*/
bgDrawable.setDrawableByLayerId(R.id.top_layer,getResources().getDrawable(R.drawable.ic_globe));/*set drawable to layer*/
image.setImageDrawable(bgDrawable);/*set drawable to image*/
Here R.drawable.border
is my drawable, R.id.bg_layer
and top_layer
are ids of items of layerlist in drawable
I hope its work for you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With