首页 > 解决方案 > Android Recycleview 多个 ViewTypes 在 kotlin 中不起作用

问题描述

我有一个应用程序,它使用房间数据库在 recycleview 中显示数据。当我从不同的表中单独加载数据时,它工作正常。但是我想在具有多种视图类型的单个回收视图中显示两个表中的数据,我知道如何在房间中组合表,但它不起作用。当我加载数据时,我在 recycleview 中得到空卡。这是我到目前为止所尝试的。我的适配器类

class CategoriesAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

companion object {
    private const val TYPE_CATEGORIES = 0
    private const val TYPE_ARTICLES = 1
}

private val items: MutableList<Any> by lazy {
    ArrayList<Any>()
}

fun setItems(list: List<Any>) {
    items.addAll(list)
    notifyDataSetChanged()
}


override fun getItemViewType(position: Int): Int {
    return if (items[position] is Categories) TYPE_CATEGORIES  else TYPE_ARTICLES
}


override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    return when (viewType) {
        TYPE_CATEGORIES -> CategoriesViewHolder.create(viewGroup)
        else -> ArticlesViewHolder.create(viewGroup)
    }
}


override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    when (holder) {
        is CategoriesViewHolder -> {
            if (items[position] is Categories)
                holder.bind(items[position] as Categories)
        }
        is ArticlesViewHolder -> {
            if (items[position] is Articles)
                holder.bind(items[position] as Articles)
        }
    }
}


override fun getItemCount(): Int {
    return items.size
}

}

class CategoriesViewHolder (parent: View) : RecyclerView.ViewHolder(parent) {

val textView: TextView = parent.findViewById(R.id.categories_textView)

fun bind(category: Categories) {
    textView.text = category.categoryName



 }

companion object {
    fun create(parent: ViewGroup): CategoriesViewHolder {
        return CategoriesViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.categories_item_layout, parent, false))
    }
}
}

class ArticlesViewHolder (parent: View) : RecyclerView.ViewHolder(parent) {

val textView: TextView = parent.findViewById(R.id.titleText)

fun bind(articles : Articles) {
    textView.text = articles.articleName

}

companion object {
    fun create(parent: ViewGroup): ArticlesViewHolder {
        return ArticlesViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.article_item_layout, parent, false))
    }
}
}

这就是我从我的活动中设置数据的方式

 val db = AppDatabase.getDatabase(applicationContext)
    dao = db.articleDao()

    val recyclerView = findViewById<RecyclerView>(R.id.categories_recycle_view)
    recyclerView.layoutManager = LinearLayoutManager(this)
    recyclerView.adapter = CategoriesAdapter()
    adapter.setItems(dao.getAllArticlesAndCategories())

任何人都可以帮忙。Ps 我是 kotlin 的新手

标签: androidkotlinandroid-recyclerviewandroid-room

解决方案


代替

 adapter.setItems(dao.getAllArticlesAndCategories())

使用实时数据观察器避免在主线程上进行处理,并在实时数据的观察功能中进行调试,以确认您从数据库接收到正确的数据。


推荐阅读