目录
卡片式布局
虽然现在MaterialTest中已经应用了非常多的Material Design效果,不过界面上最主要的一块区域还处于空白状态。这块区域通常用来放置应用的主体内容,准备使用一些精美的水果图片来填充这部分区域
为了要让水果图片也能Material化,会使用卡片式布局的效果。卡片式布局也是Materials Design中提出的一个新概念,它可以让页面中的元素看起来就像在卡片中一样,并且还能拥有圆角和投影
卡片式布局效果的重要控件:MaterialCardView
MaterialCardView是用于实现卡片式布局效果的重要控件,由Material库提供
实际上,MaterialCardView也是一个FrameLayout,只是额外提供了圆角和阴影等效果,看上去会有
立体的感觉
使用之前需要添加一个Glide库的依赖,在app/build.gradle文件中dependencies闭包声明:
implementation 'com.github.bumptech.glide:glide:4.9.0'
Glide是一个超级强大的开源图片加载库,它不仅可以用于加载本地图片,还可以加载网络图片、GIF图片甚至是本地视频。最重要的是,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">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/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" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@drawable/ic_done" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
...
</androidx.drawerlayout.widget.DrawerLayout>
这里在CoordinatorLayout中添加了一个RecyclerView,给它指定一个id,然后将宽度和高度都设置为match_parent,这样RecyclerView就占满了整个布局的空间
接着定义一个实体类Fruit,Fruit类中只有两个字段:name表示水果的名字,imageId表示水果对应图片的资源id
class Fruit(val name: String, val imageId: Int)