首页 > 解决方案 > kotlin中的getParcelable无法正确解析Android对象模型

问题描述

我使用@Parcelize 使数据类 Parcelable 像

@Parcelize
data class QuestionBO(val title: String, val options: List<String>, val correctOptionIndex: Int,
                      val dateCreated: Date, val tags: List<String>, val questionType: Int,
                      val userID: String, val userName: String, val totalLikes: Int,
                      val imageUrl: String) : Parcelable {
    constructor() : this("", emptyList(), 1, Date(), emptyList(), 3, ""
            , "", 34, "")
}

并调用并将数据传递给片段

supportFragmentManager.beginTransaction().add(
                QuestionFragment.newInstance(singleQuestion), "QuestionFragment").commit()

新实例方法

companion object {
        private const val KEY_QUESTION_BO = "key_question_bo"

        fun newInstance(aQuestion: QuestionBO) = QuestionFragment().apply {
            arguments = Bundle(2).apply {
                putParcelable(KEY_QUESTION_BO, aQuestion)
            }
        }
    }

onViewCreated我正在使用类似的参数来获取它

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        if(arguments != null){
            mQuestionBO = arguments!!.getParcelable<QuestionBO>(KEY_QUESTION_BO) as Nothing?

            /*var bundle = arguments!!.getBundle("bundle")
            bundle.getParcelable<QuestionBO>(KEY_QUESTION_BO)*/
        }
    }

笔记

我调试参数它在 onViewCreated 中显示数据但不将其转换为 QuestionBO

在此处输入图像描述

给定的语句有什么问题!!!

arguments!!.getParcelable<QuestionBO>(KEY_QUESTION_BO) as Nothing?

标签: androidkotlinparcelable

解决方案


首先,我很确定你应该使用getParcelable<QuestionBO>(KEY_QUESTION_BO) as QuestionBO?

然后从我从你的调试器中看到的,result.mMap.value[0]确实被识别为一个QuestionBO对象。

否则对我来说看起来不错。


推荐阅读