lannyf
lannyf

Reputation: 11025

how dynamically assign ring color

we could define a ring drawable and use it in layout xml file, as sample copied below,

is it possible to define a ring drawable and in runtime change the color dynamically? The use case is in the list item it may have different ring color for the ring in different item.

search and could not find a good solution, appreciated if someone have some suggestions.

<ImageView
                    android:layout_width="10dp"
                    android:layout_height="10dp"
                    android:src="@drawable/ring" />

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:top="4dp"
    android:right="4dp"
    android:bottom="4dp"
    android:left="4dp">
    <shape
        android:shape="oval">
        <solid android:color="#4d4d4d" />
    </shape>
</item>
<item>
    <shape
        android:shape="oval">
        <stroke android:width="2dp"
            android:color="#4d4d4d"/>
    </shape>
</item>

Upvotes: 1

Views: 205

Answers (1)

Arjun saini
Arjun saini

Reputation: 4182

First Put the Id to your layer draw able like that

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/shape1"
        android:top="4dp"
        android:right="4dp"
        android:bottom="4dp"
        android:left="4dp">
        <shape
            android:shape="oval">
            <solid android:color="#4d4d4d" />
        </shape>
    </item>
    <item
        android:id="@+id/shape2"

        >
        <shape

            android:shape="oval">
            <stroke android:width="2dp"
                android:color="#4d4d4d"/>
        </shape>
    </item>
    </layer-list>

Code...

LayerDrawable shape = (LayerDrawable) ContextCompat.getDrawable(demo.this,R.drawable.ring);
GradientDrawable gradientDrawable1 = (GradientDrawable) shape.findDrawableByLayerId(R.id.shape1);

GradientDrawable gradientDrawable2 = (GradientDrawable) shape.findDrawableByLayerId(R.id.shape2);

gradientDrawable1.setColor(ContextCompat.getColor(demo.this,R.color.color_first));

gradientDrawable2.setColor(ContextCompat.getColor(demo.this,R.color.color_second));// changing to black color

ImageView imageView=(ImageView)findViewById(R.id.imageview);
imageView.setBackground(shape);

enter image description here

Upvotes: 1

Related Questions