android - 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 的新手
解决方案
代替
adapter.setItems(dao.getAllArticlesAndCategories())
使用实时数据观察器避免在主线程上进行处理,并在实时数据的观察功能中进行调试,以确认您从数据库接收到正确的数据。
推荐阅读
- windows - unity windowed mode size 在不同的屏幕分辨率上是不同的
- typescript - 将铯与 TypeScript 一起使用?
- python - 用于跨蓝图共享资源的 Flask 配置
- apache-spark - 使用没有 partitionBy 的重新分区的 Spark parquet 文件数
- reactjs - React Native MapBox 获取点击位置
- mysql - Mysql:获取今天日期的记录
- python - 我如何将(-0.143704570332567-1.2618680524722614j)转换为 sklearn fit 方法可以使用的东西?
- javascript - 带有样式组件的提取样式的循环依赖
- ios - LongPressGesture NavigationLink满屏后NavigationView无法下拉
- ios - 在 iOS 中存储和检索不同的声音