android - 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?
解决方案
首先,我很确定你应该使用getParcelable<QuestionBO>(KEY_QUESTION_BO) as QuestionBO?
然后从我从你的调试器中看到的,result.mMap.value[0]
确实被识别为一个QuestionBO
对象。
否则对我来说看起来不错。
推荐阅读
- c# - 防止 Web API 中多个数据库调用发生冲突
- java - 获取数据时出现 OutOfBoundsException
- highcharts - 在 Highchart 中,如何更改多轴图表中所有图例符号的高度?
- elasticsearch - ElasticSearch - 按特定字段删除文档
- python - lxml:具有节点相同元素的while循环
- amazon-web-services - 将与模式匹配的 Cloudwatch 日志发送到 SQS 队列
- python - 将数据库中的列与python代码中获取的变量进行比较
- c++ - 如何在结构的成员函数中使用结构成员?
- git - Git -- 在 gitattributes 中设置 text=auto 和 eol=lf
- angular - Angular 5 模式验证不适用于动态响应式表单