虽然这个时候的项目中已经使用了很多Material Design效果,但是在主页面上还是一片空白,这个时候就用一些水果图片来填充这个区域
为了让水果图片也能Material化,这次就学习如何实现卡片式布局的效果
CardView
这个就是用于实现卡片布局效果的控件,由v7库提供,实际上CardView也是一个FrameLayout,但是会额外提供圆型和阴影的效果,看上去会有立体的感觉
基本用法,
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:elevation="5dp"
app:cardCornerRadius="4dp">
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
首先定义了CardView布局,通过app:cardCornerRadius属性指定卡片圆角的弧度,数值越大弧度越大,android:elevation属性指定卡片的高度,高度值越大,投影范围越大,、
这里为了演示,放了一个TextView,那么这个TextView就会显示在一张卡片当中了
下面要使用以前学过的知识,使用RecyclerView来填充整个项目,就是之前的水果列表
这里要使用到RecyclerView、CardView这几个控件,因此要在app/build.gradle文件中声明这些库的依赖
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile 'com.android.support:design:26.1.0'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.android.support:recyclerview-v7:26.1.0'
compile 'com.android.support:cardview-v7:26.1.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
}
注意最后一行声明的,这里添加一个Glide库的依赖,这是一个强大的图片加载库,用于加载本地的图片,或者是网络上的,只要一行代码就可以实现,这里使用它加载水果图片
修改activity_main.xml中的代码
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
android:layout_width="match_parent"
android:layout_height="match_parent"
>
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"