Here are two pictures.
on Lollipop:
on Pre-Lollipop:
To solve the "shadow space" issue for PRE-L versions, you can dynamically update the CardView margin by negative values to compensate the space.
To get the actual shadow space:
shadowSpaceLeft = getPaddingLeft() - getContentPaddingLeft();
To fix the margin:
layoutParams.leftMargin -= shadowSpaceLeft;
This will work for all Android versions since we are getting the padding values and the contentPadding values dynamically.
For example, here is a class that does it whenever we set new layout params:
public class NoPaddingCardView extends CardView {
public NoPaddingCardView(Context context) {
super(context);
init();
}
public NoPaddingCardView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public NoPaddingCardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
// Optional: Prevent pre-L from adding inner card padding
setPreventCornerOverlap(false);
// Optional: make Lollipop and above add shadow padding to match pre-L padding
setUseCompatPadding(true);
}
@Override
public void setLayoutParams(ViewGroup.LayoutParams params) {
// FIX shadow padding
if (params instanceof MarginLayoutParams) {
MarginLayoutParams layoutParams = (MarginLayoutParams) params;
layoutParams.bottomMargin -= (getPaddingBottom() - getContentPaddingBottom());
layoutParams.leftMargin -= (getPaddingLeft() - getContentPaddingLeft());
layoutParams.rightMargin -= (getPaddingRight() - getContentPaddingRight());
layoutParams.topMargin -= (getPaddingTop() - getContentPaddingTop());
}
super.setLayoutParams(params);
}
}