介绍
CardView 是Android 5.0 所推出的组件, 它是用于实现卡片式布局的重要组件, 以前由appcompat-v7 库提供,现在是androidx.appcompat。CardView 是 FrameLayout 的子类,只是单独提供了圆角与阴影的效果,看起来立体感更强、更加美观。CardView 一般被使用在如 ListView、GridView、RecyclerView 等列表视图的子项(item)布局中。
XML属性
CardView 支持的 XML 属性
XML属性 | 描述 |
app:cardBackgroundColor | 卡片视图的背景颜色 |
app:cardCornerRadius | 卡片视图的圆角半径 |
app:cardElevation | 卡片视图阴影的大小 |
app: cardMaxElevation | 卡片视图最大阴影的大小 |
app: cardPreventCornerOverlap | 防止卡片内容边角的重叠 |
app: cardUseCompatPadding | 保持内边距的计算方式与以前的版本相同 |
例子
CardView的布局效果
编写布局文件
在布局管理器中使用该组件需要先在build.gradle 文件的 dependencies 节点中添加 CardView 依赖库的代码。具体代码如下:
implementation 'androidx.appcompat:appcompat:1.1.0'
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--CardView组件-->
<androidx.cardview.widget.CardView
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<!--水平线性布局管理器-->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="150dp"
android:orientation="horizontal">
<!--图像组件-->
<ImageView
android:layout_width="150dp"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:scaleType="centerCrop"
android:src="@drawable/img01" />
<!--垂直线性布局管理器-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="保卫骡的岛入门"
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="连小刻都看得懂的教学"
android:textColor="#000000"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
编写CardViewActivity
public class CardViewActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
CardView cardView = (CardView)findViewById(R.id.cardView);
cardView.setRadius(10); //设置卡片视图的圆角半径
cardView.setCardElevation(10); //设置卡片视图阴影部分大小
cardView.setContentPadding(5,5,5,5); //设置卡片视图与内容的边距
}
}
效果