AndroidX學(xué)習(xí)之---CardView

介紹

官方文檔

CardView 是用圓角和陰影來實(shí)現(xiàn)Material Design卡片圖案。通常我們?cè)诹斜砩险故鞠嗤膬?nèi)容時(shí),使用cardview來講這些信息保存下來,展示相同的風(fēng)格。

使用

1、添加依賴

implementation "androidx.cardview:cardview:1.0.0"

2、創(chuàng)建Cards

說明:

  1. CardView 內(nèi)部作為視圖組包含多個(gè)widget時(shí),這些視圖會(huì)重疊顯示,需要借助其他布局來達(dá)到預(yù)期效果;因?yàn)樗且粋€(gè)FrameLayout ,所以這一點(diǎn)就不能理解了。

  2. cardBackgroundColor:配置卡片的背景se

    cardCornerRadius:配置圓角的半徑

    cardElevation:配置陰影的高度,高度越大陰影越明顯

    contentPadding:配置內(nèi)部邊距

 <androidx.cardview.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        card_view:cardBackgroundColor="#cfcfcf"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="5dp"
        card_view:contentPadding="10dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="aaaaaaaaaaaaaaaaaaa" />
    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        card_view:cardBackgroundColor="#cfcfcf"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="5dp"
        card_view:contentPadding="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="bbbbbbbbbbbbbbb" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="cccccccccccccccccc" />
        </LinearLayout>
    </androidx.cardview.widget.CardView>

注意:

如果使用CardView時(shí),設(shè)置了精確的尺寸,那么由于陰影繪制的原因,會(huì)導(dǎo)致適配時(shí)出現(xiàn)達(dá)不到預(yù)期!!!!

兩種解決方案:

  1. 區(qū)分版本來設(shè)置精確的尺寸進(jìn)行適配;

  2. 使用setUseCompatPadding(true)來達(dá)到cardview內(nèi)部填充邊距;

源碼分析:

CardView的源碼比較簡(jiǎn)單,其繼承自FrameLayout , 需要重點(diǎn)關(guān)注的是內(nèi)部的static代碼塊,這里針對(duì)不同的版本,對(duì)CardViewImpl的實(shí)現(xiàn)不同,也就說明了繪制陰影的方式不同。從onMeasure()方法看到主要區(qū)分了針對(duì)高于API21和低與版本的處理。

public class CardView extends FrameLayout {

    private static final int[] COLOR_BACKGROUND_ATTR = {android.R.attr.colorBackground};
    private static final CardViewImpl IMPL;

    static {
        if (Build.VERSION.SDK_INT >= 21) {
            IMPL = new CardViewApi21Impl();
        } else if (Build.VERSION.SDK_INT >= 17) {
            IMPL = new CardViewApi17Impl();
        } else {
            IMPL = new CardViewBaseImpl();
        }
        IMPL.initStatic();
    }
    
     public CardView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CardView, defStyleAttr,
                R.style.CardView);
        ColorStateList backgroundColor;
        if (a.hasValue(R.styleable.CardView_cardBackgroundColor)) {
            backgroundColor = a.getColorStateList(R.styleable.CardView_cardBackgroundColor);
        } else {
            // There isn't one set, so we'll compute one based on the theme
            final TypedArray aa = getContext().obtainStyledAttributes(COLOR_BACKGROUND_ATTR);
            final int themeColorBackground = aa.getColor(0, 0);
            aa.recycle();

            // If the theme colorBackground is light, use our own light color, otherwise dark
            final float[] hsv = new float[3];
            Color.colorToHSV(themeColorBackground, hsv);
            backgroundColor = ColorStateList.valueOf(hsv[2] > 0.5f
                    ? getResources().getColor(R.color.cardview_light_background)
                    : getResources().getColor(R.color.cardview_dark_background));
        }
        float radius = a.getDimension(R.styleable.CardView_cardCornerRadius, 0);
        float elevation = a.getDimension(R.styleable.CardView_cardElevation, 0);
        float maxElevation = a.getDimension(R.styleable.CardView_cardMaxElevation, 0);
        mCompatPadding = a.getBoolean(R.styleable.CardView_cardUseCompatPadding, false);
        mPreventCornerOverlap = a.getBoolean(R.styleable.CardView_cardPreventCornerOverlap, true);
        int defaultPadding = a.getDimensionPixelSize(R.styleable.CardView_contentPadding, 0);
        mContentPadding.left = a.getDimensionPixelSize(R.styleable.CardView_contentPaddingLeft,
                defaultPadding);
        mContentPadding.top = a.getDimensionPixelSize(R.styleable.CardView_contentPaddingTop,
                defaultPadding);
        mContentPadding.right = a.getDimensionPixelSize(R.styleable.CardView_contentPaddingRight,
                defaultPadding);
        mContentPadding.bottom = a.getDimensionPixelSize(R.styleable.CardView_contentPaddingBottom,
                defaultPadding);
        if (elevation > maxElevation) {
            maxElevation = elevation;
        }
        mUserSetMinWidth = a.getDimensionPixelSize(R.styleable.CardView_android_minWidth, 0);
        mUserSetMinHeight = a.getDimensionPixelSize(R.styleable.CardView_android_minHeight, 0);
        a.recycle();

         //下面這個(gè)方法針對(duì)不同的api版本也走向不同
        IMPL.initialize(mCardViewDelegate, context, backgroundColor, radius,
                elevation, maxElevation);
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (!(IMPL instanceof CardViewApi21Impl)) {
            final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
            switch (widthMode) {
                case MeasureSpec.EXACTLY:
                case MeasureSpec.AT_MOST:
                    final int minWidth = (int) Math.ceil(IMPL.getMinWidth(mCardViewDelegate));
                    widthMeasureSpec = MeasureSpec.makeMeasureSpec(Math.max(minWidth,
                            MeasureSpec.getSize(widthMeasureSpec)), widthMode);
                    break;
                case MeasureSpec.UNSPECIFIED:
                    // Do nothing
                    break;
            }

            final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
            switch (heightMode) {
                case MeasureSpec.EXACTLY:
                case MeasureSpec.AT_MOST:
                    final int minHeight = (int) Math.ceil(IMPL.getMinHeight(mCardViewDelegate));
                    heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.max(minHeight,
                            MeasureSpec.getSize(heightMeasureSpec)), heightMode);
                    break;
                case MeasureSpec.UNSPECIFIED:
                    // Do nothing
                    break;
            }
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
    
 public void setMaxCardElevation(float maxElevation) {
        IMPL.setMaxElevation(mCardViewDelegate, maxElevation);
    }
    
  public void setUseCompatPadding(boolean useCompatPadding) {
        if (mCompatPadding != useCompatPadding) {
            mCompatPadding = useCompatPadding;
            IMPL.onCompatPaddingChanged(mCardViewDelegate);
        }
    }
    
}

1、API >= 21 的源碼

默認(rèn)cardview內(nèi)部是不會(huì)填充內(nèi)邊距的,也就是他的內(nèi)容區(qū)域是占滿了cardview的全部區(qū)域的,由于圓角陰影就會(huì)導(dǎo)致內(nèi)容區(qū)域在圓角重疊的位置無法顯示,如果要顯示全部?jī)?nèi)容,那么就需要手動(dòng)去配置內(nèi)部邊距。

class CardViewApi21Impl implements CardViewImpl {

    @Override
    public void initialize(CardViewDelegate cardView, Context context,
                ColorStateList backgroundColor, float radius, float elevation, float maxElevation) {
        final RoundRectDrawable background = new RoundRectDrawable(backgroundColor, radius);
        cardView.setCardBackground(background);

        View view = cardView.getCardView();
        view.setClipToOutline(true);
        view.setElevation(elevation);
        setMaxElevation(cardView, maxElevation);
    }
    
     @Override
    public void setRadius(CardViewDelegate cardView, float radius) {
        getCardBackground(cardView).setRadius(radius);
    }
    
    @Override
    public void onCompatPaddingChanged(CardViewDelegate cardView) {
        setMaxElevation(cardView, getMaxElevation(cardView));
    }
    
        @Override
    public void setMaxElevation(CardViewDelegate cardView, float maxElevation) {
        getCardBackground(cardView).setPadding(maxElevation,
                cardView.getUseCompatPadding(), cardView.getPreventCornerOverlap());
        updatePadding(cardView);
    }
    
    //.....
}


//RoundRectDrawable.java
class RoundRectDrawable extends Drawable {

    //這個(gè)標(biāo)記就是是否在cardView填充內(nèi)部邊距
    private boolean mInsetForPadding = false;
    
        void setPadding(float padding, boolean insetForPadding, boolean insetForRadius) {
        if (padding == mPadding && mInsetForPadding == insetForPadding
                && mInsetForRadius == insetForRadius) {
            return;
        }
        mPadding = padding;
        mInsetForPadding = insetForPadding;
        mInsetForRadius = insetForRadius;
        updateBounds(null);
        invalidateSelf();
    }
    
    void setRadius(float radius) {
        if (radius == mRadius) {
            return;
        }
        mRadius = radius;
        updateBounds(null);
        invalidateSelf();
    }
    
    private void updateBounds(Rect bounds) {
        if (bounds == null) {
            bounds = getBounds();
        }
        mBoundsF.set(bounds.left, bounds.top, bounds.right, bounds.bottom);
        mBoundsI.set(bounds);
        if (mInsetForPadding) {
            float vInset = RoundRectDrawableWithShadow.calculateVerticalPadding(mPadding, mRadius, mInsetForRadius);
            float hInset = RoundRectDrawableWithShadow.calculateHorizontalPadding(mPadding, mRadius, mInsetForRadius);
            mBoundsI.inset((int) Math.ceil(hInset), (int) Math.ceil(vInset));
            // to make sure they have same bounds.
            mBoundsF.set(mBoundsI);
        }
    }
}

2、API < 21 的源碼

CardViewBaseImpl

cardview的陰影部分是從cardview自己的尺寸向內(nèi)壓縮了陰影的區(qū)域,這樣就有了內(nèi)部邊距

class CardViewBaseImpl implements CardViewImpl {

    @SuppressWarnings("WeakerAccess") /* synthetic access */
    final RectF mCornerRect = new RectF();

    @Override
    public void initStatic() {
        // Draws a round rect using 7 draw operations. This is faster than using
        // canvas.drawRoundRect before JBMR1 because API 11-16 used alpha mask textures to draw
        // shapes.
        RoundRectDrawableWithShadow.sRoundRectHelper =
                new RoundRectDrawableWithShadow.RoundRectHelper() {
            @Override
            public void drawRoundRect(Canvas canvas, RectF bounds, float cornerRadius,
                    Paint paint) {
                
                //下面的代碼說明老版本的cardview的陰影是從cardview的尺寸向內(nèi)壓縮出來的
                final float twoRadius = cornerRadius * 2;
                final float innerWidth = bounds.width() - twoRadius - 1;
                final float innerHeight = bounds.height() - twoRadius - 1;
                if (cornerRadius >= 1f) {
                    // increment corner radius to account for half pixels.
                    float roundedCornerRadius = cornerRadius + .5f;
                    mCornerRect.set(-roundedCornerRadius, -roundedCornerRadius, roundedCornerRadius,
                            roundedCornerRadius);
                    int saved = canvas.save();
                    canvas.translate(bounds.left + roundedCornerRadius,
                            bounds.top + roundedCornerRadius);
                    canvas.drawArc(mCornerRect, 180, 90, true, paint);
                    canvas.translate(innerWidth, 0);
                    canvas.rotate(90);
                    canvas.drawArc(mCornerRect, 180, 90, true, paint);
                    canvas.translate(innerHeight, 0);
                    canvas.rotate(90);
                    canvas.drawArc(mCornerRect, 180, 90, true, paint);
                    canvas.translate(innerWidth, 0);
                    canvas.rotate(90);
                    canvas.drawArc(mCornerRect, 180, 90, true, paint);
                    canvas.restoreToCount(saved);
                    //draw top and bottom pieces
                    canvas.drawRect(bounds.left + roundedCornerRadius - 1f, bounds.top,
                            bounds.right - roundedCornerRadius + 1f,
                            bounds.top + roundedCornerRadius, paint);

                    canvas.drawRect(bounds.left + roundedCornerRadius - 1f,
                            bounds.bottom - roundedCornerRadius,
                            bounds.right - roundedCornerRadius + 1f, bounds.bottom, paint);
                }
                // center
                canvas.drawRect(bounds.left, bounds.top + cornerRadius,
                        bounds.right, bounds.bottom - cornerRadius , paint);
            }
        };
    }
}

總結(jié)

CardView繼承自FrameLayout,再使用的時(shí)候如果內(nèi)部子視圖大于1,那么最好在內(nèi)部嵌套其他的布局,否則會(huì)一直從cardview的左上角繪制,這樣會(huì)導(dǎo)致視圖重疊。

CardView的使用和源碼都比較簡(jiǎn)單,核心點(diǎn)就是內(nèi)部邊距的在適配不同版本上需要注意:5.0 之前的版本會(huì)自動(dòng)預(yù)留內(nèi)邊距,而5.0之后需要手動(dòng)配置是否需要預(yù)留內(nèi)邊距,否則默認(rèn)是不會(huì)預(yù)留內(nèi)邊距的。

技術(shù)點(diǎn):自定義view的繪制流程、自定義widget的xml屬性

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容