RecyclerView实现瀑布流布局
注意:内容来源于郭神《第二行代码》。郭神博客http://blog.csdn.net/guolin_blog
一、RecyclerView是干什么的?
简单点我们可以先把它理解为ListView的一个升级版,因为它不仅可以轻松的完成ListView的各种功能,而且还优化了ListView中存在的各种不足之处。
二、RecyclerView的基本用法
因为Android团队将RecyclerView定义在了support库当中,因此要使用这个控件,我们首先要在项目的build.gradle中添加相应的依赖库才行。
打开app/build.gradle文件,在dependencies闭包下添加如下内容
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:recyclerview-v7:24.2.1'
}
添加完之后要记得点击一下右上方的Sync Now来进行同步。然后就可以在activity_main.xml 中使用它了如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
这里要注意:因为RecyclerView不是内置在系统的SDK中,所以引用的时候要把完整的包路径写出来
这里我们先用RecyclerView来实现和ListView相同的效果如图所示:
因此这里我们和ListView一样要先准备用来展示的数据: (我们准备在每一个Item上展示一个水果的图片和它的名字即一个ImageView和TextView)
首先先定义一个水果的实体类Fruit,代码如下:
public class Fruit {
private int imageId;
private String name;
public Fruit(int imageId, String name) {
this.imageId = imageId;
this.name = name;
}
public int getImageId() {
return imageId;
}
public String getName() {
return name;
}
}
Fruit类中只有两个字段,name表示水果的名字,imageId表示水果对应图片的资源id。
然后像ListView一样需要为我们的子项指定一个我们自定义的布局,在layout目录下新建fruit-item.xml,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content">
<ImageView
android:id="@+id/fruit_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/fruit_name"
android:layout_width=