Android中CardView的使用

Android5.0中向我们介绍了一个全新的控件–CardView,从本质上看,可以将CardView看做是FrameLayout在自身之上添加了圆角和阴影效果。请注意:CardView被包装为一种布局,并且经常在ListView和RecyclerView的Item布局中,作为一种容器使用。

这里写图片描述

CardView应该被使用在显示层次性的内容时;在显示列表或网格时更应该被选择,因为这些边缘可以使得用户更容易去区分这些内容。

使用CardView

首先,假设你的布局如同下面的形式:

<FrameLayout  xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" 
android:layout_height="wrap_content"> 

<!-- Main Content View --> 
<RelativeLayout> ... </RelativeLayout> 

</FrameLayout>

为了使用上面的布局方式来创建一个卡片,首先你需要导入支持的依赖库(android-support-v7-cardview的jar包)在你的build.gradle文件中。

dependencies { 
compile 'com.android.support:cardview-v7:21.0.2' 
}

现在将FrameLayout替换为CardView,

<android.support.v7.widget.CardView  xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" 
android:layout_height="wrap_content"> 

<!-- Main Content View --> 
<RelativeLayout> ... </RelativeLayout> 

</android.support.v7.widget.CardView>

就是这样!使用依赖库能够保证你的程序稳定的兼容之前的版本;尽管在AndroidL和之前的Android版本中对其处理方式有所不同。

定制CardView

CardView提供了一个默认的elevation(意为CardView的Z轴阴影)和圆角角度,所以每一个卡片都能够在不同的设备上保持相同的外观。然而,你也可以根据自己的需求去定制这些值。

<android.support.v7.widget.CardView  xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" 
android:layout_height="wrap_content" 
card_view:cardCornerRadius="8dp" 
card_view:cardElevation="8dp"> 

<!-- Main Content View --> <RelativeLayout> ... </RelativeLayout> 

</android.support.v7.widget.CardView>

注意:cardElevation属性被用来决定阴影的大小以及柔和度,以至于可以逼真的模拟出对于深度效果的描述。

添加波纹点击效果

默认情况,CardView是不可点击的,并且没有任何的触摸反馈效果。触摸反馈动画在用户点击CardView时可以给用户以视觉上的反馈。为了实现这种行为,你必须提供一下属性:

<android.support.v7.widget.CardView 
... 
android:clickable="true" 
android:foreground="?android:attr/selectableItemBackground"> 
</android.support.v7.widget.CardView>

使用android:foreground=”?android:attr/selectableItemBackground”可以使CardView点击产生波纹的效果,有触摸点向外扩散。

对更早的版本的支持

在AndroidL之前的设备上,CardView为了支持圆角的效果加上了padding,圆角剪裁操作可以算是很昂贵的操作。相似的,对阴影效果来说,在AndroidL之前,也会提供padding去绘制阴影面积,这些内容的padding是和elevation属性相关的,按照文档:

padding值为: 
左右两边的值为:maxCardElevation + (1 - cos45) * cornerRadius 
上下两边的值为:maxCardElevation * 1.5 + (1 - cos45) * cornerRadius

因此,如果你需要给自己的内容加上padding的话,需要使用新的属性:card_view:contentPadding
相似的,如果改变CardView的背景,也需要使用新的属性:card_view:cardBackgroundColor

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值