还记得我们一共学过了多少UI控件了吗?都掌握的怎么样啊。
安卓中一些常用控件学习得差不多了,今天再来学习一个新的控件CardView,在实际开发中也有非常高的地位。
一、CardView简介
CardView是Android 5.0系统引入的控件,相当于FragmentLayout布局控件然后添加圆角及阴影的效果。
CardView继承自Framelayout,所以FrameLayout所有属性CardView均可以直接拿来用,不过CardView还有自己独有的属性,常用属性如下:
-
app:cardElevation:设置阴影的大小。
-
app:cardMaxElevation:设置阴影最大高度。
-
app:cardBackgroundColor:设置卡片的背景色。
-
app:cardCornerRadius:设置卡片的圆角大小。
-
app:contentPadding:设置内容的padding。
-
app:contentPaddingTop:设置内容的上padding。
-
app:contentPaddingLeft:设置内容的左padding。
-
app:contentPaddingRight:设置内容的右padding。
-
app:contentPaddingBottom:设置内容的底padding。
-
app:cardUseCompatPadding:是否使用CompatPadding。
-
app:cardPreventConrerOverlap:是否使用PreventCornerOverlap。
这里有一点需要值得注意,之前学习到的控件属性都是android:开头的,而这里所列的属性是app:开头的,如果继续使用默认的会提示找不见对应属性,需要我们定义一个app命名空间,在布局文件中需要加入xmlns:app="http://schemas.android.com/apk/res-auto"语句,具体见后续案例,这里不作过多介绍,后续再详细学习。
二、CardView示例1
接下来通过几个简单的小示例程序来进一步学习CardView。
继续使用WidgetSample工程的advancedviewsample模块,首先需要添加支持库,具体操作步骤同之前分享的揭开RecyclerView庐山真面目,这里不再重复分享。这次输入的关键字是cardview,即可完成CardView依赖库的添加。
在src/main/res/layout/目录下创建cardview_layout.xml文件,在其中填充如下代码片段:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="70dp"
android:text="正常使用效果"
android:gravity="center_horizontal|center_vertical"
android:textSize="20sp"
android:padding="10dp"
android:layout_margin="10dp"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:cardBackgroundColor="#669900"
app:cardCornerRadius="10dp">
<TextView
android:layout_width="match_parent&#