Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically change drawable and shape color in layer list?

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?

like image 490
user5578746 Avatar asked Nov 18 '15 22:11

user5578746


People also ask

How do I change the color of an image in 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.


1 Answers

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

like image 73
Android Geek Avatar answered Oct 04 '22 18:10

Android Geek