with - android trapezoid shape xml




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

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?


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

I would prefer to make shape in shape and to add padding to the inner shape...

Like this:

<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#2E3135" />
            <corners
                android:bottomLeftRadius="8dp"
                android:bottomRightRadius="8dp"
                android:topLeftRadius="8dp"
                android:topRightRadius="8dp" />
        </shape>
    </item>
    <item
        android:bottom="3dp"
        android:left="3dp"
        android:right="3dp"
        android:top="3dp">
        <shape android:shape="rectangle">
            <solid android:color="#DFDFE0" />
            <corners
                android:bottomLeftRadius="5dp"
                android:bottomRightRadius="5dp"
                android:topLeftRadius="5dp"
                android:topRightRadius="5dp" />
        </shape>
    </item>
</layer-list>

UPDATE: I found that the corners of the inner shape should be smaller for a better look... For a different proportions you will need to test which inner radius, outer radius and stroke size(the padding) is best for your solution





shapedrawable