androidclip

Android: how to clip only top rounded corners


I'm creating a ScrollView with a FrameLayout inside. I want to design it so that only the top corners are rounded on the ScrollView. I've created a drawable shape as follows

<shape>
    <solid android:color="@color/white"/>
    <corners
        android:bottomLeftRadius="0dp"
        android:bottomRightRadius="0dp"
        android:topLeftRadius="16dp"
        android:topRightRadius="16dp"/>
    <padding android:padding="0dp"/>
</shape>

I've then set the following on the ScrollView

 scrollView.setOutlineProvider(ViewOutlineProvider.BACKGROUND);
 scrollView.setClipToOutline(true);

When i try scrolling, the elements in my FrameLayout end up protruding through the outline of my scrollview

Excuse the drawing, but what i'm looking to achieve

However if i instead create a shape like so

<shape>
    <solid android:color="@color/white"/>
    <corners
        android:radius="16dp"/>
    <padding android:padding="0dp"/>
</shape> 

It clips it just fine.

So how would i clip it if i only want the top to be cornered.


Solution

  • I've managed to get this working by creating a custom ViewOutlineProvider and using that instead of a background value

    ViewOutlineProvider mViewOutlineProvider = new ViewOutlineProvider() {
        @Override
        public void getOutline(final View view, final Outline outline) {
            float cornerRadiusDP = 16f;
            float cornerRadius = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, cornerRadiusDP, getResources().getDisplayMetrics());
                outline.setRoundRect(0, 0, view.getWidth(), (int)(view.getHeight() + cornerRadius), cornerRadius);
            }
    };
    scrollView.setOutlineProvider(mViewOutlineProvider);
    scrollView.setClipToOutline(true);