zl程序教程

您现在的位置是:首页 >  APP

当前栏目

Android CardView卡片布局详解(八)

2023-04-18 14:28:10 时间

一、CardView简介

CardView卡片布局是Android 5.0之后推出的布局效果,一般用于显示阴影和圆角效果的UI。CardView继承自FrameLayout帧布局,所以它其实还是一个布局。

卡片布局示例:

二、CardView属性介绍

  • cardBackgroundColor:设置背景色,CardView为了实现阴影效果,内部已经消耗掉了 Background属性,所以新增cardBackgroundColor属性用于设置背景色。
  • cardCornerRadius:设置圆角半径。
  • contentPadding:设置内部padding,CardView内部消耗掉了padding属性,新增了contentPadding属性。
  • cardElevation:设置阴影大小
  • cardUseCompatPadding:默认为false,用于5.0及以上,true则添加额外的padding绘制阴影。
  • cardPreventCornerOverlap:默认为true,用于5.0及以下,添加额外的padding,防止内容和圆角重叠。

有关cardUseCompatPadding和cardPreventCornerOverlap的属性讲解,可以参考这位大神的讲解。https://www.jianshu.com/p/a44da1d6a4cf


三、CardView使用示例

在布局文件中使用CardView卡片布局。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    tools:context=".MainActivity08">

    <androidx.cardview.widget.CardView
        android:id="@+id/card"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        app:cardBackgroundColor="#ffffff"
        app:cardCornerRadius="10dp"
        app:cardElevation="10dp"
        app:cardPreventCornerOverlap="true"
        app:cardUseCompatPadding="false">

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            app:srcCompat="@drawable/winter" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="120dp"
            android:layout_marginRight="10dp"
            android:text="美丽风景,美丽风景,美丽风景,美丽风景,美丽风景,美丽风景。"
            android:textColor="#000000"
            android:textSize="14sp" />
    </androidx.cardview.widget.CardView>

</RelativeLayout>

上面布局效果展示:

 

原创不易,点个赞再走呗。。。