0

I have a number of shapes, and I have one view. I need to dynamically (i.e. programmatically) select a shape to set as the background of my view based on user inputs. So my question: who do I programmatically turn a shape into a ShapeDrawable or such?

I already look at How to change shape color dynamically?. Those posts assume the shape is already attached to a view. But me all my shapes are free agents.

Community
  • 1
  • 1
Cote Mounyo
  • 13,817
  • 23
  • 66
  • 87

2 Answers2

1

It seems that is does not work with ShapeDrawable, but take a look at my GradientDrawable example:

you can create gradient drawable dynamically.. use below class

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

}

and use this class as below

SomeDrawable drawable = new SomeDrawable(Color.parseColor("Start Color Code"),Color.parseColor("Center Color Code"),Color.parseColor("End Color Code"),1,Color.BLACK,00);
yourLayout.setBackgroundDrawable(drawable);
Sanket Kachhela
  • 10,861
  • 8
  • 50
  • 75
0

I just found that I can do

myview.setBackgroundResource(R.drawable.my_shape)
Cote Mounyo
  • 13,817
  • 23
  • 66
  • 87