RecyclerView基本使用(二)-- 返回不同类型的View

本文介绍了如何在RecyclerView中展示不同类型的Item。通过创建多个XML布局文件和对应的数据源,结合不同的ViewHolder,实现在同一个RecyclerView中显示Image和TextView组成的复合视图。详细讲解了Adapter中的方法,包括判断View类型、实例化ViewHolder以及在onBindViewHolder中加载数据。
摘要由CSDN通过智能技术生成

上一篇博客RecyclerView的基本使用讲述了Recycler最基本的使用方法,这篇博客主要围绕如何在一个RecyclerView呈现不同的Item。

要实现在RecyclerView呈现复合Item,主要要在RecyclerView.adapter中的以下三个方法做处理:

  • getItemViewType()
  • onCreateViewHolder()
  • onBindViewHolder()

具体实现

首先,要呈现出不同Item,那么说明Item会有多个XML文件和对应的不同数据源。简便起见,假设我们的项目中有两种不同的Item,一种是单纯的Image,另外一种则是由多个TextView组成。

数据源定义如下:

private ArrayList<Object> getSampleArrayList() {
    ArrayList<Object> items = new ArrayList<>();
    items.add(new User("Dany Targaryen", "Valyria"));
    items.add(new User("Rob Stark", "Winterfell"));
    items.add("image");
    items.add(new User("Jon Snow", "Castle Black"));
    items.add("image");
    items.add(new User("Tyrion Lanister", "King's Landing"));
    return items;
}

可以看到,有User和单纯的String两种数据。这两种数据对应的布局文件也不同,那么必然导致需要使用不同的ViewHolder:
ViewHolder1.java

public class ViewHolder1 extends RecyclerView.ViewHolder {
   

    private TextView label1, label2;

    public ViewHolder1(View v) {
        super(v);
        label1 = (TextView) v.findViewById(R.id.text1);
        label2 = (TextView) v.findViewById(R.id.text2);
    }

    public TextView getLabel1() {
        return label1;
    }

    public void setLabel1(TextView label1) {
        this.label1 = label1;
    }

    public TextView getLabel2() {
        return label2;
    }

    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值