安卓5.0引进了一个新的控件叫做CardView
本质上可以看作是一个带有圆角和阴影以及海拔的FrameLayout
CardView
可以包裹一个布局,并且经常在布局中作为每一项的container。
使用
依赖:compile 'com.android.support:cardview-v7:23.2.1'
在布局中使用
<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>
设置
<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:cardBackgroundColor="#E6E6E6"
card_view:cardCornerRadius="8dp"
card_view:cardElevation="8dp">
<!-- Main Content View -->
<RelativeLayout>
...
</RelativeLayout>
</android.support.v7.widget.CardView>
使用代码设置:
CardView card = ...
card.setCardBackgroundColor(Color.parseColor("#E6E6E6"));
card.setMaxCardElevation(0.0);
card.setRadius(5.0);
``
#增加波纹效果
android:clickable=”true”
android:foreground=”?android:attr/selectableItemBackground”>
“`
版本支持
在L之前的版本,CardView
通过增加间距来支持圆角半径,同样的对于阴影,L之前的版本,`CardView 通过添加内容之间的间距和阴影的绘制来获得阴影。
card_view:contentPadding
按照文档:两边的间距的值等于maxCardElevation + (1 - cos45) * cornerRadius
上下间距的值:maxCardElevation*1.5 + (1 - cos45) * cornerRadius.
如果要指定自定义间距的值
card_view:cardBackgroundColor`
更换背景: