Div_D Div_D - 20 days ago 10
Android Question

RecyclerView with nested lists data

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


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.

Answer

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

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
          }

      }

Now look what you have:

  • For getItemCount() return the list size.

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

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

Simple.

Comments