CardView has extra margin in each edge on Pre-Lollipop

前端 未结 7 760
闹比i
闹比i 2020-12-24 14:05

Here are two pictures.

on Lollipop: \"on

on Pre-Lollipop:

7条回答
  •  醉梦人生
    2020-12-24 14:35

    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);
        }
    }
    

提交回复
热议问题