卡片式控件CardView&源码分析

前言

       CardView作为卡片控件是在Android5.0系统引入的,继承于FragmentLayout布局在里面添加圆角阴影的效果,Google在5.0中引入了MD设计Elevation和Z轴位移,目的就是突出不同元素之间的层次关系,在显示列表或者网格时候更加的炫酷,说到这里便有跃跃欲试的感觉,Let's Go!

效果~


Part 1、CardView卡片的简单应用

配置

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. dependencies {  
  2.     compile fileTree(include: ['*.jar'], dir: 'libs')  
  3.     androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {  
  4.         exclude group: 'com.android.support', module: 'support-annotations'  
  5.     })  
  6.     compile 'com.android.support:cardview-v7:25.0.1'  
  7. }  

代码:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <android.support.v7.widget.CardView  
  2.     android:id="@+id/cardview"  
  3.     android:layout_width="150dp"  
  4.     android:layout_height="150dp"  
  5.     app:cardCornerRadius="8dp"  
  6.     app:cardElevation="10dp">  
  7.   
  8.     <ImageView  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:src="@drawable/pic2"/>  
  12.   
  13. </android.support.v7.widget.CardView>  
  14.   
  15. <Space  
  16.     android:layout_width="match_parent"  
  17.     android:layout_height="20dp"/>  
  18.   
  19. <android.support.v7.widget.CardView  
  20.     android:layout_width="150dp"  
  21.     android:layout_height="150dp"  
  22.     app:cardCornerRadius="8dp"  
  23.     app:cardElevation="10dp">  
  24.   
  25.     <TextView  
  26.         android:layout_width="wrap_content"  
  27.         android:layout_height="150dp"  
  28.         android:background="#5f00"  
  29.         android:singleLine="false"  
  30.         android:text="无论谁说什么 都只有你一个而已"  
  31.         />  
  32.   
  33. </android.support.v7.widget.CardView>  
tips:

1、Space : 空格控件

2、app:cardCornerRadius="" : 设置卡片圆角的半径

3、app:cardElevation="" : Z轴的值

效果~

上面的坑:

1、相同cardElevation值,阴影效果4.4要强于5.1

2、5.1中文字紧贴着圆角,不美观

解决方案:

1、在低版本中设置CardElevation之后CardView会自动留出空间供阴影显示,而Lollipop之后需要手动进行设置Margin边距来预留空间,这里我们定义两套布局(当然你也可以写两个dimen.xml)。

在低版本设置

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. android:layout_margin="0dp"  
在高版本设置(一般和 CardElevation 阴影大小相同)

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. android:layout_margin="16dp"    
2、对于文字紧贴圆角的问题,需要设置paddingContent属性来兼容,这里给出设置android:padding和android:contentPadding的效果来进行比对,差别很明显便不做解释


从上面可知需要进行设置contentPadding,但这里注意的是因为5.0以上会自动图片进行裁剪已经很美观了不需要在设置contentPadding。


接下来为CardView设置水波纹效果

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. android:clickable="true"  
  2. android:foreground="?attr/selectableItemBackground"  
当然你也可以自己用ripple来定义水波纹,上面的代码只在5.0以后有效,之前是没有效果的,这里也别忘了设置clickable

最后为CardView设置动画(这里只是点击让它阴影变大)

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. android:stateListAnimator="@drawable/state_animator"  
state_animator.xml:
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <selector  
  2.     xmlns:android="http://schemas.android.com/apk/res/android">  
  3.         <item  
  4.             android:state_pressed="true">  
  5.                 <objectAnimator  
  6.                     android:duration="@android:integer/config_shortAnimTime"  
  7.                     android:propertyName="translationZ"  
  8.                     android:valueTo="15dp"  
  9.                     android:valueType="floatType"  
  10.                 ></objectAnimator>  
  11.         </item>  
  12.         <item>  
  13.                 <objectAnimator  
  14.                     android:duration="@android:integer/config_shortAnimTime"  
  15.                     android:propertyName="translationZ"  
  16.                     android:valueTo="0dp"  
  17.                     android:valueType="floatType"></objectAnimator>  
  18.         </item>  
  19. </selector>  

效果~


附上设置基本属性

app:cardBackgroundColor这是设置背景颜色 
app:cardCornerRadius这是设置圆角大小 
app:cardElevation这是设置z轴的阴影 
app:cardMaxElevation这是设置z轴的最大高度值 
app:cardUseCompatPadding是否使用CompatPadding 
app:cardPreventCornerOverlap是否使用PreventCornerOverlap 
app:contentPadding 设置内容的padding 
app:contentPaddingLeft 设置内容的左padding 
app:contentPaddingTop 设置内容的上padding 
app:contentPaddingRight 设置内容的右padding 
app:contentPaddingBottom 设置内容的底padding


Part 2、CardView源码分析

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class CardView extends FrameLayout {  

CardView继承FrameLayout,也就有了FrameLayout层次结构的特点

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. private static final CardViewImpl IMPL;  
  2.   
  3. static {  
  4.     if (Build.VERSION.SDK_INT >= 21) {  
  5.         IMPL = new CardViewApi21();  
  6.     } else if (Build.VERSION.SDK_INT >= 17) {  
  7.         IMPL = new CardViewJellybeanMr1();  
  8.     } else {  
  9.         IMPL = new CardViewGingerbread();  
  10.     }  
  11.     IMPL.initStatic();  
  12. }  

一初始化便对版本进行判断,来定义不同的实现类

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. final Rect mContentPadding = new Rect();  
  2.   
  3. final Rect mShadowBounds = new Rect();  
看到相应的字段可知一个是设置内容内边距,一个设置阴影的大小

进而进入构造方法

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. private void initialize(Context context, AttributeSet attrs, int defStyleAttr) {  
  2.     TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CardView, defStyleAttr,  
  3.             R.style.CardView);  
  4.     ColorStateList backgroundColor;  
  5.     if (a.hasValue(R.styleable.CardView_cardBackgroundColor)) {  
  6.         backgroundColor = a.getColorStateList(R.styleable.CardView_cardBackgroundColor);  
  7.     } else {  
  8.         // There isn't one set, so we'll compute one based on the theme  
  9.         final TypedArray aa = getContext().obtainStyledAttributes(COLOR_BACKGROUND_ATTR);  
  10.         final int themeColorBackground = aa.getColor(00);  
  11.         aa.recycle();  
这里它判断你是否设置了cardBackgroundColor,如果没有则从主题中获取android.R.attr.colorBackground属性

查看onMesure方法

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  3.     if (!(IMPL instanceof CardViewApi21)) {  
  4.         final int widthMode = MeasureSpec.getMode(widthMeasureSpec);  
  5.         switch (widthMode) {  
  6.             case MeasureSpec.EXACTLY:  
  7.             case MeasureSpec.AT_MOST:  
  8.                 final int minWidth = (int) Math.ceil(IMPL.getMinWidth(mCardViewDelegate));  
  9.                 widthMeasureSpec = MeasureSpec.makeMeasureSpec(Math.max(minWidth,  
  10.                         MeasureSpec.getSize(widthMeasureSpec)), widthMode);  
  11.                 break;  
  12.         }  
  13.   
  14.         final int heightMode = MeasureSpec.getMode(heightMeasureSpec);  
  15.         switch (heightMode) {  
  16.             case MeasureSpec.EXACTLY:  
  17.             case MeasureSpec.AT_MOST:  
  18.                 final int minHeight = (int) Math.ceil(IMPL.getMinHeight(mCardViewDelegate));  
  19.                 heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.max(minHeight,  
  20.                         MeasureSpec.getSize(heightMeasureSpec)), heightMode);  
  21.                 break;  
  22.         }  
  23.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  24.     } else {  
  25.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  26.     }  
  27. }  
这里判断如果API大于5.0则不处理,如果小于则预留出阴影的空间

这里来进入CardViewApi21类

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. class CardViewApi21 implements CardViewImpl {  
  2.   
  3.     @Override  
  4.     public void initialize(CardViewDelegate cardView, Context context,  
  5.                 ColorStateList backgroundColor, float radius, float elevation, float maxElevation) {  
  6.         final RoundRectDrawable background = new RoundRectDrawable(backgroundColor, radius);//圆角矩形  
  7.         cardView.setCardBackground(background);//为CardView设置圆角  
  8.   
  9.         View view = cardView.getCardView();//得到CardView控件  
  10.         view.setClipToOutline(true);//进行裁剪  
  11.         view.setElevation(elevation);//设置阴影大小  
  12.         setMaxElevation(cardView, maxElevation);//设置最大阴影大小  
  13.     }  
这个类目的就是突出API21版本下的独特特性,既然是设置阴影必然是设置padding,进而查看
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2. public void updatePadding(CardViewDelegate cardView) {  
  3.     if (!cardView.getUseCompatPadding()) {  
  4.         cardView.setShadowPadding(0000);  
  5.         return;  
  6.     }  
  7.     float elevation = getMaxElevation(cardView);  
  8.     final float radius = getRadius(cardView);  
  9.     int hPadding = (int) Math.ceil(RoundRectDrawableWithShadow  
  10.             .calculateHorizontalPadding(elevation, radius, cardView.getPreventCornerOverlap()));  
  11.     int vPadding = (int) Math.ceil(RoundRectDrawableWithShadow  
  12.             .calculateVerticalPadding(elevation, radius, cardView.getPreventCornerOverlap()));  
  13.     cardView.setShadowPadding(hPadding, vPadding, hPadding, vPadding);  
  14. }  
计算出相应的padding值回传给CardViewDelegate对象CardView,但CardViewDelegate是个接口,通过查看CardView可知CardViewDelegate是CardView的内部类
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. private final CardViewDelegate mCardViewDelegate = new CardViewDelegate() {  
  2.      private Drawable mCardBackground;  
进入setShadowPadding方法
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public void setShadowPadding(int left, int top, int right, int bottom) {  
  2.     mShadowBounds.set(left, top, right, bottom);  
  3.     CardView.super.setPadding(left + mContentPadding.left, top + mContentPadding.top,  
  4.             right + mContentPadding.right, bottom + mContentPadding.bottom);  
  5. }  
这里为mShadowBounds设置了边距,也为父级View设置了边距,所以会出现如果你设置了contentPadding之后边缘会显现出CardView的背景

那为什么设置padding没有效果呢?

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2. public void setPadding(int left, int top, int right, int bottom) {  
  3.     // NO OP  
  4. }  
  5.   
  6. public void setPaddingRelative(int start, int top, int end, int bottom) {  
  7.     // NO OP  
  8. }  
可以看到CardView的setPadding并没有做任何的操作所以不显示。至此分析完毕
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值