android - 如何在 Kotlin 中从活动中调用片段的方法并将数据同时发送到片段
问题描述
我需要使用活动事件调用片段的方法onStart()
。我找到了很多答案,但我在 Kotlin 中需要 Java。同时 onStart 事件将值发送到片段。我认为我可以使用 ViewModel 执行此操作,但我尝试在模型中设置值,但出现错误“不匹配”。
public class StatusStudent: ViewModel(){
var status = MutableLiveData<Int>()
fun setStatus(newStatus: Int ){
status = newStatus //Here Error "Mismatch"
}
}
解决方案
问题:您正在尝试分配Int
to MutableLiveData<Int>
。
解决方案:您想要做的是使用setterMutableLiveData<Int>
分配包装器持有的值:
public class StatusStudent: ViewModel() {
val status = MutableLiveData<Int>()
fun setStatus(newStatus: Int) {
status.value = newStatus
}
}
注意:status
应该很可能是 a val
(而不是 a var
),因为您已经在使用可变包装器并且不想更改它的引用,而是更改值!
推荐阅读
- loops - 如何正确循环遍历数组?
- python - 在 Python 中使用 30 年基线计算气候异常
- google-cloud-python - 演讲:无服务器上的 long_running_recognize
- java - Arduino - Xbee - Java 通讯
- android - 如何防止我的应用被用户在/从最近关闭
- java - 使用 BiConsumer 时如何理解 Java8 中的方法引用
- javascript - 删除项目代码点火器
- c++ - 如何使用 winapi c++ 发送 shift+down?
- python - 当有多个相关字段加入时,我的 django 模型加入了错误的字段
- c# - Kinect 悬停事件处理程序