MaterialCardView with top rounded corners should clip children

Viewed 314

MaterialCardView clips its children when using rounded corners. If I use cardCornerRadius = true (which rounds all 4 corners of the card), the clipping behaves as expected -> children are not being drawn outside of the rounded area. If I try to round less corners (ie. only top corners, using ShapeAppearanceModel), then the clipping part is lost -> a top positioned child will be drawn over the rounded cornered area).

I realised that clip MaterialCardView calls setClipToOutline(shapeAppearanceModel.isRoundRect(getBoundsAsRectF())); inside of setShapeAppearanceModel, where isRoundRect returns true only if all four corners are rounded, so I tried applying clipToOutline = true on the MaterialCardView after setting the shapeAppearanceModel with top corners rounded, but with no similar result - children were still able to be drawn over the rounded part of the parent card.

What is actually triggering the clipping part and how can I force it on a top rounded shaped MaterialCardView?

LE: trial and error code:

// card is MaterialCardView
card.shapeAppearanceModel =   
    ShapeAppearanceModel()
        .toBuilder()
        .setTopRightCorner(CornerFamily.ROUNDED, cornerPx) // cornerPx = 24dp in pixels
        .setTopLeftCorner(CornerFamily.ROUNDED, cornerPx)
        .build()

card.apply {
    preventCornerOverlap = true
    clipChildren = true
    clipToOutline = true
}
card.invalidateOutline()
    
1 Answers

Apply the following configurationsif you use shape appearance overlay in order to prevent the childs to overlapping from the corners:

  • Set cardPreventCornerOverlap to true
  • Then leave everything else that has to do with the corner settings as default (just delete the values from the textboxes in the design mode).

Then you should see something like this: enter image description here

Related