1

Case 1: Show list of productName in View while sending List<Products> productList in adapter constructor.

Case 2: Show list of categoryName in View while sending List<Category> categoryList in adapter constructor.

Both the cases must use the same RecyclerView Adapter.

The adapter may have List<Object> objectList. But how can show different property of the different object in the View

ॐ Rakesh Kumar
  • 1,318
  • 1
  • 14
  • 24
  • Possible duplicate of [How to create RecyclerView with multiple view type?](https://stackoverflow.com/questions/26245139/how-to-create-recyclerview-with-multiple-view-type) – Onur D. Oct 08 '18 at 15:43
  • I wanted something different. Probably you didn't understood. @OnurD. – Mehedi Hasan Chonchol Oct 08 '18 at 16:39
  • I think I understood correctly. As you said, you can keep a list of Objects in your adapter while having multiple ViewHolders in it. A ProductViewHolder for a Product, a CategoryViewHolder for a Category object etc. After this, it all comes to putting if-else or switch-case conditions on your `getItemViewType()` method as well as `onCreateViewHolder()` – Onur D. Oct 08 '18 at 16:44
  • Not multiple view holder actually. I just wanted to use the same `viewHolder` for different `List` of Objects. – Mehedi Hasan Chonchol Oct 08 '18 at 17:22

1 Answers1

1

Check the type:

@Override
public void onBindViewHolder(WhateverHolder holder, int position) {
    Object item = itemsList.get(position);

    if (item instanceof Products) {
        Product product = (Product) item;
        //populate the ViewHolder with the information
    } else if (item instanceof Category) {
        Category category = (Category) item;
        //populate the ViewHolder
    } else {
        throw IllegalArgumentException("Invalid item: " + item.getClass().getCanonicalName()); //this is optional 
    }
}
TheWanderer
  • 16,775
  • 6
  • 49
  • 63