【问题标题】:How to access inner data classes of sealed class from a recyclerView adapter如何从 recyclerView 适配器访问密封类的内部数据类
【发布时间】:2019-06-17 13:50:34
【问题描述】:

我在为正在构建的聊天界面设置 ViewModel 数据时遇到问题,我想在聊天布局 (RecyclerView) 中显示各种不同类型的数据。这些包括: 文字、按钮、卡片视图轮播...

我已经设置了一个 Sealed 类,我希望它能够包含显示这些数据所需的所有数据类,它看起来像这样的 atm:

sealed class ChatMessage {
abstract var msgTime: Long?

sealed class Text : ChatMessage() {

    abstract val originator: String
    abstract var content: String

    data class Mine(
            override val originator: String,
            override var msgTime: Long?,
            override var content: String
    ) : Text()

    data class Agent(
            override val originator: String,
            override var msgTime: Long?,
            override var content: String

    ) : Text()

}

sealed class Button : ChatMessage(){

    abstract val title: String
    abstract val actionText: String

    data class General (
            override var title: String,
            override var actionText: String,
            override var msgTime: Long?
            ) : Button()
}
}

在我的适配器中,我将它添加到 arrayList 以供显示:

    var itemsOld: ArrayList<ChatMessage> = ArrayList()

并添加一个新项目如下:

fun addNewMessage(model: ChatMessage.Text.Mine){

    itemsOld.add(model)

    itemsOld.sortBy { it.msgTime }

   // mRecyclerView!!.smoothScrollToPosition(itemCount - 1)

    MyApplication.appContext!!.runOnUiThread {
        // Stuff that updates the UI
        notifyDataSetChanged()
    }
}

但我无法访问

itemsOld[0].content

itemsOld[0].originator

只有

itemsOld[0].msgTime

如何构造数据类,以便我有一个可以由 ArrayList 实现的父类,并且可以容纳我可能需要同时在 RecyclerView 中显示的所有数据类?

【问题讨论】:

    标签: android kotlin android-recyclerview sealed-class


    【解决方案1】:

    这些字段在 ChatMessage 模型中均不可用。您需要将类型转换为特定的数据类或使用 when() 表达式为您进行转换。希望这会有所帮助,干杯!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      • 2015-04-16
      相关资源
      最近更新 更多