RecyclerView的基本用法、横向/纵向/网格/瀑布流布局显示及点击事件

ListView只能纵向显示而且还要优化(即手动写代码实现缓存好子项布局文件及其里面控件),而Recycler除了优化好这些,还可以实现横向/纵向/网格/瀑布流布局显示(关键:只需改RecyclerVIew.setLayoutManager(布局类对象实例)中的布局类对象,这个参数的布局不同,就可以实现不同子项显示方式:横向/纵向/网格/瀑布流布局

  • 纵向LinearLayoutManager.VERTICAL:

LinearLayoutManager默认VERTICAL排列,setLayoutManager(布局类对象实例)传入LinearLayoutManager实例对象即可

  • 横向LinearLayoutManager.HORIZONTAL:

先LinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL),在setLayoutManager(布局类对象)传入LinearLayoutManager实例对象即可

  • 网格GridLayoutManager:

setLayoutManager(布局类对象实例)传入GridLayoutManager实例对象即可,可先为GridLayoutManager实例对象设置点属性先

  • 瀑布流StaggeredGridLayoutManager:

setLayoutManager(布局类对象实例)传入StaggeredGridLayoutManager实例对象即可,StaggeredGridLayoutManager也可以设置瀑布流的排列是VERTICAL还是HORIZONTAL)

  1. RecyclerView的基本用法:

①打开app/build.gradle文件,在dependencies闭包内添加RecyclerView的依赖:

implementation 'com.android.support:recyclerview-v7:28.0.0'(V7:28.0.0仅仅是版本),可以通过Android Studio的Design视图直接添加RecyclerView,就会自动提示添加依赖了

②在要使用RecyclerView的XML中添加RecyclerView控件

<android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

<android.support.v7.widget.RecyclerView这里要用完整的路径

③定义实体类,作为子项里显示的数据的载体

public class Fruit {
    private String name;

    private int imageId;

    public Fruit(String name, int imageId) {
        this.name = name;
        this.imageId = imageId;
    }

    public String getName() {
        return name;
    }

    public int getImageId() {
        return imageId;
    }
}

④自定义子项布局(这里不同,则子项的样式也不同,而改setLayoutManager(***LayoutManager)仅仅是子项的布局和排列不同)

fruit_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 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="wrap_content"
        android:layout_height=&#
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值