首页 > 解决方案 > 如何在 Kotlin 中从活动中调用片段的方法并将数据同时发送到片段

问题描述

我需要使用活动事件调用片段的方法onStart()。我找到了很多答案,但我在 Kotlin 中需要 Java。同时 onStart 事件将值发送到片段。我认为我可以使用 ViewModel 执行此操作,但我尝试在模型中设置值,但出现错误“不匹配”。

public class StatusStudent: ViewModel(){
    var  status = MutableLiveData<Int>()
    fun setStatus(newStatus: Int ){
        status = newStatus //Here Error "Mismatch"
    }
}

标签: androidandroid-fragmentskotlin

解决方案


问题:您正在尝试分配Intto MutableLiveData<Int>

解决方案:您想要做的是使用setterMutableLiveData<Int>分配包装器持有的值:

public class StatusStudent: ViewModel() {
    val status = MutableLiveData<Int>()
    fun setStatus(newStatus: Int) {
        status.value = newStatus
    }
}

注意:status应该很可能是 a val(而不是 a var),因为您已经在使用可变包装器并且不想更改它的引用,而是更改值!


推荐阅读