Android View Clipping
Try subclassing ViewGroup and overriding the OnDraw method as follows, substituting in values for RADIUS_IN_PIXELS:
@Overrideprotected void onDraw(Canvas canvas) { Path clipPath = new Path(); clipPath.addRoundRect(new RectF(canvas.getClipBounds()), RADIUS_IN_PIXELS, RADIUS_IN_PIXELS, Path.Direction.CW); canvas.clipPath(clipPath); super.onDraw(canvas);}
...and also create a custom drawable like this called something like 'rounded', substituting in YOUR_BACKGROUND_COLOR and RADIUS_IN_DP, making sure to match the rounding of the rectangle in DP to your previous clipping radius in PX:
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="RADIUS_IN_DP" /> <solid android:color="YOUR_BACKGROUND_COLOR"/></shape>
Then you can use that subclass in your layout, adding the lines
android:background="@drawable/rounded"android:clipChildren="true"
All children will clip to the bounds you specify in the OnDraw() override, and a background will be added based on your 'rounded' drawable.
Make sure layout
has a background with rounded corners.
Kotlin
layout.outlineProvider = ViewOutlineProvider.BACKGROUNDlayout.clipToOutline = true
Java
layout.setOutlineProvider(ViewOutlineProvider.BACKGROUND);layout.setClipToOutline(true);
Create custom layout with overridden onDraw(Canvas canvas)
call canvas.clipRect(0, 0, mCanvasWidth, mCanvasHeight);
this will clip all views that goes out of layout boundary.
And don't forget to call setWillNotDraw(false)
in constructor, so your onDraw will execute