Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 405
srain Avatar asked Jul 16 '13 04:07

srain


2 Answers

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);
like image 108
srain Avatar answered Nov 20 '22 22:11

srain


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

like image 3
Sir NIkolay Cesar The First Avatar answered Nov 20 '22 22:11

Sir NIkolay Cesar The First