Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a drawable Shape programmatically (Android)

i'm making a custom TextView (Java class) and i'm having trouble "to translate" the line (on "original TextView" xml)

android:background="@drawable/myDrawableShape"

to a java void to change the color of the "myDrawableShape"

myDrawableShape.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#ffafafaf" />
<corners android:radius="15dp" />

I'll get the color to set from a String, the void to change the color programmatically could be (for example)

void colorSet(String color)

Thanks in advance!

like image 996
ieselisra Avatar asked Dec 07 '25 08:12

ieselisra


1 Answers

You can then create your Shape Drawable in Java itself using below code.

public Drawable getRoundRect() {
    RoundRectShape rectShape = new RoundRectShape(new float[]{
            10, 10, 10, 10,
            10, 10, 10, 10
    }, null, null);

    ShapeDrawable shapeDrawable = new ShapeDrawable(rectShape);
    shapeDrawable.getPaint().setColor(Color.parseColor("#FF0000"));
    shapeDrawable.getPaint().setStyle(Paint.Style.FILL);
    shapeDrawable.getPaint().setAntiAlias(true);
    shapeDrawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
    return shapeDrawable;
}
like image 85
Muthukrishnan Rajendran Avatar answered Dec 08 '25 21:12

Muthukrishnan Rajendran