Goofy
Goofy

Reputation: 6128

How to pass the color value dynamically to xml

i have a xml which will draw oval shape , the code is below:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#61118"/>
    <stroke android:width="1sp" android:color="#1B434D" />
</shape>

Now i here android:color="#61118" i need to pass the value from java class, Is it possible?

If not is there any alternative way?

Upvotes: 4

Views: 3717

Answers (2)

nicopico
nicopico

Reputation: 3636

Sadly you cannot pass arguments to XML Drawables.

If you don't have too many different values, you can use a <level-list> and provide different versions of your shape.

Then you would change the level associated with your drawable to change the color using Drawable.setLevel(int).


my_drawable.xml

<level-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:maxLevel="0">
        <shape android:shape="oval">
            <solid android:color="@color/red"/>
            <stroke android:width="1sp" android:color="@color/border" />
        </shape>
    </item>
    <item android:maxLevel="1">
        <shape android:shape="oval">
            <solid android:color="@color/green"/>
            <stroke android:width="1sp" android:color="@color/border" />
        </shape>
    </item>
    <item android:maxLevel="2">
        <shape android:shape="oval">
            <solid android:color="@color/blue"/>
            <stroke android:width="1sp" android:color="@color/blue" />
        </shape>
    </item>
</level-list>

MyActivity.java

// myView is a View (or a subclass of View) 
// with background set to R.drawable.my_drawable
myView.getBackground().setLevel(0); // Set color to red
myView.getBackground().setLevel(1); // Set color to green
myView.getBackground().setLevel(2); // Set color to blue

// myImageView is an ImageView with its source
// set to R.drawable.my_drawable
myImageView.setImageLevel(0); // Set color to red
myImageView.setImageLevel(1); // Set color to green
myImageView.setImageLevel(2); // Set color to blue

Upvotes: 5

sudocoder
sudocoder

Reputation: 1173

Yes, you can change the color of a shape dynamically. Assume your xml is in, 'res/drawable/oval_shape.xml'

GradientDrawable shape = (GradientDrawable) getResources().getDrawable(R.drawable.oval_shape);
int argb = 0x12345678;
shape.setBackground( argb );

if you would like to change the border color

int width = 1;
int argb = 0x87654321;
shape.setStroke( width, argb );

This solution provides more flexibility over using a level-list because you are not tied to using a view to set the level.

Upvotes: 1

Related Questions