Android CardView使用详解

来源:互联网 发布:唐砖精校版txt下载知轩 编辑:程序博客网 时间:2024/04/27 22:50

转至:http://www.w2bc.com/Article/36229


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

原文出处

原文来自:Using the CardView


0 0
原创粉丝点击