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?
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.
Try this:
GradientDrawable bg = (GradientDrawable) relative_layout.getBackground();
bg.setCornerRadii();
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));
int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { setBackgroundDrawable(); } else { setBackground(); }
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.