Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create android shape background programmatically?

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

like image 960
DolDurma Avatar asked Feb 18 '15 08:02

DolDurma


People also ask

How do you make a drawable shape?

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 can change button background drawable in android programmatically?

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.


1 Answers

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.

like image 121
rahul shah Avatar answered Sep 18 '22 19:09

rahul shah