Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Shape dynamically

I have a shape object defined in XML like below:

<shape android:shape="rectangle">
    <gradient
        android:startColor="#333"
        android:centerColor="#DDD"
        android:endColor="#333"/>
    <stroke android:width="1dp" android:color="#FF333333" />
</shape>

I want to create an equal object in my code. I created a GradientDrawable as below:

gradientDrawable1.setColors(new int[] { 0x333, 0xDDD, 0x333 });
gradientDrawable1.setOrientation(Orientation.TOP_BOTTOM);

But I don't know how to create a Stroke(?) and then assign both Stroke and GradientDrawable to Shape

Any idea?

like image 279
Ali Behzadian Nejad Avatar asked Jul 20 '13 07:07

Ali Behzadian Nejad


1 Answers

Example:

import android.graphics.drawable.GradientDrawable;

public class SomeDrawable extends GradientDrawable {

    public SomeDrawable(int pStartColor, int pCenterColor, int pEndColor, int pStrokeWidth, int pStrokeColor, float cornerRadius) {
        super(Orientation.BOTTOM_TOP,new int[]{pStartColor,pCenterColor,pEndColor});
        setStroke(pStrokeWidth,pStrokeColor);
        setShape(GradientDrawable.RECTANGLE);
        setCornerRadius(cornerRadius);
    }

}

Usage:

public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SomeDrawable vDrawable = new SomeDrawable(Color.BLACK,Color.GREEN,Color.LTGRAY,2,Color.RED,50);
        View vView = new View(this);
        vView.setBackgroundDrawable(vDrawable);
        setContentView(vView);
    }


}

Result:

Drawable result image

like image 83
S.D. Avatar answered Oct 26 '22 20:10

S.D.