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

标签 android android-recyclerview

案例一: 显示 productName 的列表在 View发送时 List<Products> productList在适配器构造函数中。

案例二: 显示 categoryName 的列表在 View发送时 List<Category> categoryList在适配器构造函数中。

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

适配器可能有 List<Object> objectList .但是如何在 View 中显示不同对象的不同属性?

最佳答案

检查类型:

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

关于android - 是否可以创建一个动态的 RecyclerView 适配器来接受任何对象列表 <Object> 的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52705163/

相关文章:

android - Top ActionBar 覆盖页面内容

android - 如何使用 Firebase 数据库在 Recycler View 中检索特定数据?

android - 在 SwipeRefreshLayout 中使用 RecyclerView 时,底部的滚动效果不会出现

android - 我们如何区分 RecyclerView.OnScrollListener 中的用户滚动和 scrollToPosition() 滚动?

android - RecyclerView 部分和来自 Firebase 的数据

java - 从已编译的 apk 中恢复丢失的代码

java - 我怎样才能永远在Android应用程序中保留一个线程?

android - 有没有办法使用 Volley 将标签添加到 NetworkImageView

Android:如何使 Kotlin 中所有对象列表的类型转换器(用于 Room)通用

android - RecyclerView 中的 CheckBox 无法正常运行