Create a form dynamically

I have a form object defined in XML, as shown 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 shown 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?

+6
source share
3 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); } } 

Using:

 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

+7
source

this should work confidently , 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 the color stroke, the beginning, the center is defined inside colors.xml as:

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

if you want to do this in code, first check which instance of the class returns res.getDrawable (resId), for example:

 Drawable d = res.getDrawable(R.drawable.shape) Log.d(TAG, "d: " + d) 
-5
source

Source: https://habr.com/ru/post/949884/


All Articles