如何从recyclerView适配器访问密封类的内部数据类

时间:2019-06-17 13:50:34

标签: android kotlin android-recyclerview sealed-class

我在为正在建立的聊天界面设置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中的所有数据类?

1 个答案:

答案 0 :(得分:1)

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