Reputation: 4243
I would like edit the background of layout in runtime. My image drawable is in the class and I would like to set the image with corners like background of the layout. How to do this?
Upvotes: 1
Views: 2272
Reputation: 684
Try this:
GradientDrawable bg = (GradientDrawable) relative_layout.getBackground();
bg.setCornerRadii();
Upvotes: 1
Reputation: 10661
setCornerRadius(float value) will set all four corners with the same value.
So it also has the method setCornerRadii(float []radii), which can be used to set corners of all four sides, from top-left, top-right, bottom-right, bottom-left;
setCornerRadii(float []radii)
Specify radii for each of the 4 corners. For each corner, the array contains 2 values, [X_radius, Y_radius]. The corners are ordered top-left, top-right, bottom-right, bottom-left. This property is honored only when the shape is of type RECTANGLE.
GradientDrawable drawable = (GradientDrawable) view.getBackground();
drawable.setCornerRadii(radii);
OR
float values[] = {1.1f, 2.2f, 1.5f, 3.3f};
GradientDrawable drawable = (GradientDrawable) view.getBackground();
drawable.setCornerRadii(values);
This means, top-left corner is 1.1f, top-right corner is 2.2, bottom-right corner is 1.5f and finally bottom-left corner is 3.3f.
Upvotes: 4
Reputation: 1909
To create Shape Drawable Programetically
public static void createShapeDrawable(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 }); // set corner Radious
shape.setColor(backgroundColor);
shape.setStroke(3, borderColor);
v.setBackgroundDrawable(shape);
}
Upvotes: 0
Reputation: 2494
int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { setBackgroundDrawable(); } else { setBackground(); }
see : https://stackoverflow.com/a/11947755/3329488
Upvotes: 0
Reputation: 739
Create drawables resource for your normal and curved background and place them in res/drawable/
folder.
For example:
box.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
</shape>
box_curved.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp" />
</shape>
Then at runtime, change background by :
view.setBackground(getResources().getDrawable(R.drawable.box));
or
view.setBackground(getResources().getDrawable(R.drawable.box_curved));
Upvotes: 0