How to create this shape programmatically?
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:padding="10dp" android:shape="rectangle"> <solid android:color="#e67e22"/> <corners android:topLeftRadius="0dp" android:topRightRadius="0dp" android:bottomLeftRadius="5dp" android:bottomRightRadius="5dp"/> </shape>
I've tried this simple function which gets corners, colors and sets that to shape:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.category_header); GradientDrawable drawable = (GradientDrawable) linearLayout.getDrawable(); float[] values = { 0.2f, 0.2f, 0.2f, 0.2f }; drawable.setCornerRadii(values);
But I got this error:
The method getDrawable() is undefined for the type LinearLayout
Creating shape drawables is done in XML with the <item> and <shape> elements. The <item> element is the enclosing parent of <shape> . It defines attributes like the width and height of the shape, but that is possible only if your project is API 23 and above.
How to set Background of button in Android programmatically? setBackgroundResource() method is used to change the button background programmatically. setBackgroundResource(int id) accepts id of drawable resource and applies the background to the button.
You can do it like this:
public static void customView(View v, int backgroundColor, int borderColor) { GradientDrawable shape = new GradientDrawable(); shape.setShape(GradientDrawable.RECTANGLE); shape.setCornerRadii(new float[] { 8, 8, 8, 8, 0, 0, 0, 0 }); shape.setColor(backgroundColor); shape.setStroke(3, borderColor); v.setBackground(shape); }
See the documentation for the meaning of setCornerRadii
params.
You can use this function throughout your app and can put border and background color of your choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With