Home » Android » Android drawable with parameters

Android drawable with parameters

Posted by: admin May 14, 2020 Leave a comment

Questions:

Is it possible to have something like

drawable/myshape.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">

    <solid android:color="{0}" />
</shape>

and then from java class take this drawable passing values for parameters. Something like

Drawable myshape = ???.getDrawableWithParameters(R.drawable.myshape, 0x00ff00);
How to&Answers:

If you create a shape the way you have shown in the example, then it will be accessible as a GradientDrawable.

GradientDrawable d = (GradientDrawable) getResources().getDrawable(R.drawable.yourid);

If you take a look at the documentation (link above) you can see all the functions, you can access from a GradientDrawable object. You can also set the background and border color and width later, programmatically using this object.

I’m not 100% sure, that every time you create a shape in xml, you will get a GradientDrawable. I needed to modifiy some properties on a shape myself, and figured it out seeing ClassCastExceptions when trying to cast to other types of Drawables