您的位置:首页 > 移动开发 > Android开发

Android应用开发:CardView的使用及兼容

2017-02-10 09:05 471 查看
引言

在Google I/O 2014上,Google公布了Android L Preview版本,此版本的UI有了非常大的改变,很炫很给力!同时,Google也给出了两个可以向下兼容的控件放到了V7包中,分别是RecyclerView和CardView,这篇博文就说一下怎么使用CardView。

CardView的包在哪?

虽然说CardView整合到了V7中,但是在support-v7中并不能发现,通过查看sdk extra路径下的文件可以发现,其名字叫cardview-v7。

这个路径下就有cardview相关的东西了,包括已经打包好的aar包。

依赖

如果应用是以Gradle构建的,引用CardView就很简单了:

[html] view plain copy print?

dependencies {

compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:cardview-v7:21.0.0-rc1'

}

如果Gradle提示找不到,就证明你的SDK需要更新了,把Google support包更新到最新吧。

如果没有用Gradle构建,就需要找到jar包引用进来,而jar包隐藏在CardView的aar文件中:

以压缩包方式打开aar,提取出其中的class.jar,这个jar文件就可以当作库文件进行依赖了。

依赖添加完成后,进行编译会发现出现minSdk错误,cardview-v7的minsdk为“L",其实CardView能够向下兼容到2.0。

在Android gradle tools 0.11版本后,可以通过xml中的tools配置进行节点替换,而AndrodiStudio对gradle tools的支持更好一些,其ParentIDE Intellij都不行,所以目前我能找到的正常使用CardView的IDE及配置办法只有在AndroidStudio中,不过这也是趋势,早用早好的事情。

解决办法:

在使用CardView的工程的AndroidManifest.xml中:

[html] view plain copy print?

<uses-sdk

xmlns:tools="http://schemas.android.com/tools"

tools:node="replace" />

意思就是在做AndroidoManifest.xml编译时,采用替换的策略,即全部使用build.gradle中定义的属性作为最终属性。添加完成后,再次编译,问题解决。

使用

在使用CardVIew之前,要明白CardView是个什么东西。CardView如Linearlayout、Framelayout一样都是ViewGroup,即其他控件的容器。CardView继承于Framelayout,所以Framelayout的属性他都有,同时CardView还有几个特殊的属性:

在API21(Android L)等级以上拥有属性elevation,意为CardView的Z轴阴影,只有L平台有效。只能通过xml中的elevation属性指定;

其余(2.0以上)有属性cardBackgroundColor,意为CardView的卡片颜色,只能通过xml的cardBackgroundColor进行指定;

其余(2.0以上)有属性cardConerRadius,意为CardView卡片的四角圆角矩形程度,单位dimen(dp px sp),可以通过xml指定,也可以通过代码中的setRadius指定。

示例:

[html] view plain copy print?

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

android:id="@+id/cardview"

app:cardCornerRadius="8dp"

app:cardBackgroundColor="@color/black"

android:layout_margin="8dp"

android:layout_height="80dp"

android:layout_width="match_parent">
<TextView
android:text="TextView in CardView"
android:layout_gravity="center"
android:textSize="26sp"
android:textColor="@color/l_white"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />


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

(<a href="http://www.dztcsd.com/">资质代办</a>)

效果图:

作者: sun春菊 
 
来源:慕课网
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: