目录
12.5 卡片式布局
虽然现在 MaterialTest 中已经应用了非常多的 Material Design 效果,不过你会发现,界面上最主要的一块区域还处于空白状态。这块区域通常用来放置应用的主体内容,我准备使用一些精 美的水果图片来填充这部分区域。
为了要让水果图片也能 Material 化,本节中我们将会学习如何实现卡片式布局的效果。卡片式 布局也是 Materials Design 中提出的一个新概念,它可以让页面中的元素看起来就像在卡片中 一样,并且还能拥有圆角和投影,下面我们就开始具体学习一下。
12.5.1 MaterialCardView
MaterialCardView 是用于实现卡片式布局效果的重要控件,由 Material 库提供。实际上, MaterialCardView 也是一个 FrameLayout ,只是额外提供了圆角和阴影等效果,看上去会有立体的感觉。
我们先来看一下 MaterialCardView 的基本用法吧,其实非常简单,如下所示:
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="4dp"
app:elevation="5dp">
<TextView
android:id="@+id/infoText"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.google.android.material.card.MaterialCardView>
这里定义了一个 MaterialCardView 布局,我们可以通过 app:cardCornerRadius 属性指定卡 片圆角的弧度,数值越大,圆角的弧度也越大。另外,还可以通过 app:elevation 属性指定卡片的高度:高度值越大,投影范围也越大,但是投影效果越淡;高度值越小,投影范围也越 小,但是投影效果越浓。这一点和 FloatingActionButton 是一致的。
然后,我们在 MaterialCardView 布局中放置了一个 TextView ,那么这个 TextView 就会显示在 一张卡片当中了,就是这么简单。
但是,我们显然不可能在如此宽阔的一块空白区域内只放置一张卡片。为了能够充分利用屏幕 的空间,这里我准备综合运用一下第 4 章中学到的知识,使用 RecyclerView 填充 MaterialTest 项目的主界面部分。还记得之前实现过的水果列表效果吗?这次我们将升级一下,实现一个高配版的水果列表效果。
既然是要实现水果列表,那么首先肯定需要准备许多张水果图片,这里我从网上挑选了一些精 美的水果图片,将它们复制到了项目当中(资源下载方式见前言)。
然后,由于我们还需要用到 RecyclerView ,因此必须在 app/build.gradle 文件中声明库的依 赖:
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'com.github.bumptech.glide:glide:4.9.0'
...
}
上述声明的第二行是添加了Glide 库的依赖。Glide 是一个超级强大的开源图片加载库,它不仅 可以用于加载本地图片,还可以加载网络图片、GIF图片甚至是本地视频。最重要的是,Glide 的用法非常简单,只需几行代码就能轻松实现复杂的图片加载功能,因此这里我们准备用它来 加载水果图片。Glide 的项目主页地址是:https://github.com/bumptech/glide 。
接下来开始具体的代码实现,修改 activity_main.xml 中的代码,如下所示:
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
// Toolbar
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"