代码之家  ›  专栏  ›  技术社区  ›  Mehedi Hasan Chonchol

是否可以创建一个接受任何对象列表的动态RecyclerView适配器?

  •  1
  • Mehedi Hasan Chonchol  · 技术社区  · 7 年前

    案例1: 显示列表 productName 在里面 View List<Products> productList 在适配器构造函数中。

    案例2: categoryName 在里面 查看 发送时 List<Category> categoryList

    两种情况必须使用相同的方法 RecyclerView 适配器。

    适配器可能有 List<Object> objectList . 但是,如何才能显示不同对象的不同属性呢 查看

    1 回复  |  直到 7 年前
        1
  •  1
  •   TheWanderer    7 年前

    检查类型:

    @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 
        }
    }