How to create shape with solid, corner, stroke in Java Code?

srain picture srain · Jul 16, 2013 · Viewed 36.4k times · Source

I have a shape defined in the xml file below, now I want to change to solid color programmatically.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#DFDFE0" />

    <corners
        android:bottomLeftRadius="8dp"
        android:bottomRightRadius="8dp"
        android:topLeftRadius="8dp"
        android:topRightRadius="8dp" />

    <stroke
        android:width="3dp"
        android:color="#2E3135" />

</shape>

I think I should have a class which extends ShapeDrawable, and implements the onDraw method. Anyone knows how to?

Answer

srain picture srain · Jul 16, 2013

Finally, I worked it out!

// prepare
int strokeWidth = 5; // 5px not dp
int roundRadius = 15; // 15px not dp
int strokeColor = Color.parseColor("#2E3135");
int fillColor = Color.parseColor("#DFDFE0");

GradientDrawable gd = new GradientDrawable();
gd.setColor(fillColor);
gd.setCornerRadius(roundRadius);
gd.setStroke(strokeWidth, strokeColor);