前言
Android 5.0 版本中新增了 CardView,CardView 继承自 FrameLayout 类,具有圆角背景和阴影的 FrameLayout,并且可以设置圆角和阴影,使得控件具有立体性,也可以包含其他的布局容器和控件。
本文章向大家介绍 Android CardView 详解及使用方法和实例,主要包括 Android CardView 详解及使用方法和实例使用实例、应用技巧、基本知识点总结和需要注意事项。
一、CardView 常用属性
XML 属性 | 方法 | 介绍 |
---|---|---|
app:cardBackgroundColor | setCardBackgroundColor(int color) | 设置背景颜色 |
app:cardCornerRadius | setRadius(float radius) | 设置圆角大小 |
app:cardElevation | setCardElevation(float elevation) | 设置 z 轴的阴影 |
app:cardMaxElevation | setMaxCardElevation(float maxElevation) | 设置 z 轴的最大高度值 |
app:cardUseCompatPadding | setUseCompatPadding(boolean useCompatPadding) | 是否使用 CompatPadding 默认值为 false |
app:cardPreventCornerOverlap | setPreventCornerOverlap(boolean preventCornerOverlap) | 是否给 content 添加 padding,来阻止与圆角重叠,默认值为 true |
app:contentPadding | setContentPadding(int left, int top, int right, int bottom) | 设置内容的内边距 padding |
app:contentPaddingLeft | setContentPadding(int left, int top, int right, int bottom) | 设置内容的左边距 padding |
app:contentPaddingTop | setContentPadding(int left, int top, int right, int bottom) | 设置内容的上边距 padding |
app:contentPaddingRight | setContentPadding(int left, int top, int right, int bottom) | 设置内容的右边距 padding |
app:contentPaddingBottom | setContentPadding(int left, int top, int right, int bottom) | 设置内容的底边距 padding |
二、CardView 基础使用
1、添加依赖包
要添加 CardView 的依赖项,您必须将 Google Maven 代码库添加到项目中。在应用或模块的 build.gradle 文件中添加所需工件的依赖项:
dependencies {
implementation "androidx.cardview:cardview:1.0.0"
}
这里顺便提一下androidx
,很多朋友私信我为什么以前依赖 v7 包。简单理解为androidx
是 Google 将之前的v4
和v7
包整理后的产物,以后所有的控件都要依赖androidx
2、创建布局
在布局文件中创建 CardView 控件,使用方法跟 ViewGroup 一致,可以在 CardView 中添加一系列的子控件。一般情况下,把 CardView 当做一个父容器,里面可以包含其他子 View,在 ListView 或者 RecyclerView 中充当 item 布局使用。
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
app:contentPadding="8dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=