RecyclerView实现瀑布流布局

本文介绍了RecyclerView作为ListView升级版的用法,包括基本用法、实现横向滚动布局以及详细的瀑布流布局步骤,展示了RecyclerView的强大功能。
摘要由CSDN通过智能技术生成

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=
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值