Create a Shape dynamically

╄→гoц情女王★ 提交于 2019-12-05 05:51:39

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:

this should surely work, Try gradientDrawable1.setStroke(1, getResources().getColor(R.color.stroke));

so your code should be :

    GradientDrawable gradientDrawable1 = new GradientDrawable(Orientation.TOP_BOTTOM, new int[]{getResources().getColor(R.color.start),getResources().getColor(R.color.center),getResources().getColor(R.color.start)} );
    gradientDrawable1.setStroke(1, getResources().getColor(R.color.stroke));

where color stroke,start,center is defined inside colors.xml as:

 <color name="stroke">#FF333333</color>
 <color name="start">#333</color> 
 <color name="center">#ddd</color>

if you want to make it in the code, first inspect what class instance is returned by res.getDrawable(resId) e.g by:

Drawable d = res.getDrawable(R.drawable.shape)
Log.d(TAG, "d: " + d)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!