带有嵌套列表数据的 RecyclerView [英] RecyclerView with nested lists data

查看:39
本文介绍了带有嵌套列表数据的 RecyclerView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Recyclerview 来显示可以像这样可视化的数据:

I am using a Recyclerview to show a data that can be visualized like this:

Order
     FirstTypeOrders
       FirstTypeOrder[0]
           --title
           Item[0]
               --title
           Item[1]
               --title
           Item[2]
               --title
       FirstTypeOrder[1]
           --title
           Item[0]
               --title
           Item[1]
               --title
           Item[2]
               --title
     SecondTypeOrders
       SecondTypeOrder[0]
          --title
       SecondTypeOrder[1]
          --title

我在 getItemViewType() 中遇到了一个问题,我无法弄清楚分离视图类型的逻辑.我有三种视图类型:一种用于显示所有 FirstTypeOrders 的标题,一种用于显示 FirstTypeOrders 中的项目,一种用于显示所有 SecondTypeOrders 的标题.

I have ran into a problem in getItemViewType() where i can't figure out the logic for seperating the view types. I have three viewtypes: one for displaying title of all FirstTypeOrders, one for displaying items in FirstTypeOrders, one for displaying title of all SecondTypeOrders.

推荐答案

这里有一个想法:实际上创建一个异构列表来表示扁平列表模型

Here's one idea: Actually create a heterogeneous list to represent the flattened list model

假设您列出的每个对象都有类:FirstTypeOrderItemSecondTypeOrder.

Let's say you have classes for each object you listed: FirstTypeOrder, Item and SecondTypeOrder.

您只需遍历数据并将每个对象放入列表中即可.

You simply traverse your data and put each object in the list.

      private List<Object> mFlattenedList = new ArrayList<>();

...

      private void flatten(List<FirstTypeOrder> orders1, List<SecondTypeOrder> orders2) {

          for (FirstTypeOrder order1 : orders1) {
              mFlattenedList.add(order1);  // to get the title
              for (Item item : order1.getItems()) {
                  mFlattenedList.add(item);
              }
          }
          for (SecondTypeOrder order2 : orders2) {
              mFlattenedList.add(order2);  // to get the title
          }

      }

现在看看你有什么:

  • 对于 getItemCount() 返回列表大小.

对于 bindViewHolder(ViewHolder holder, int position),您在 position 处有一个对象,可以从中绑定数据.

For bindViewHolder(ViewHolder holder, int position), you have an object at position from which to bind data.

对于 getItemViewType(int position),使用 position 处的 instanceof 对象来确定要返回的视图类型.

For getItemViewType(int position), use instanceof object at position to determine which view type to return.

简单.

这篇关于带有嵌套列表数据的 RecyclerView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆