Java – How to Make Drawable Shapes Programmatically (Android)

How to Make Drawable Shapes Programmatically (Android)… here is a solution to the problem.

How to Make Drawable Shapes Programmatically (Android)

I’m making a custom TextView (Java class), but I’m having trouble translating” the line (on the “original TextView” xml).

android:background="@drawable/myDrawableShape"

Go to a java void to change the color of “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 the string, the void to change the color programmatically might be (for example).

void colorSet(String color)

Thanks in advance!

Solution

You can then use the following code to create a Shape Drawable in Java itself.

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;
}

Related Problems and Solutions