我有一个 Activity,其中声明了一个接口(interface),我有一个 ViewModel
类,它重写了接口(interface),我想从 Activity
调用接口(interface)的方法来进行更改ViewModel
类,但无法调用 Activity
中的方法,表示 ViewModel 类没有伴随对象,因此必须在此处初始化。如何解决?
var selection: setSelectionSubRow? = null
selection=RowSubTShirtViewModel
selection!!.setNameSelection(false)
以上代码在名称为TShirtActivity
的Activity
中。
以下代码来自 RowViewModel
类
class RowSubTShirtViewModel(private val subTShirtAdapter: SubTShirtAdapter, val context: TShirtActivity,
val tShirtBean: CommonItemBean, private val parentPosition: Int, private val position: Int) : BaseObservable() ,TShirtActivity.setSelectionSubRow{
fun getImageDrawable(): Drawable {
return if (tShirtBean.isSelected)
ContextCompat.getDrawable(context, R.drawable.green_border_circle)!!
else
ContextCompat.getDrawable(context, R.drawable.border_circle)!!
}
override fun setNameSelection(selection: Boolean) {
if (parentPosition == 6) {
if (position == 1) {
tShirtBean.isSelected = false
}
}
}
最佳答案
此行 selection=RowSubTShirtViewModel
引用 View 模型,就好像它是命名对象一样,这意味着您应该编写而不是类对象:
object RowSubTShirtViewModel {
//...
}
但是,由于情况并非如此,kotlin 告诉您不能那样引用它并且必须对其进行初始化。构造函数有很多参数让我猜测它们是什么,但本质上你必须将它们传递进来:
selection=RowSubTShirtViewModel(/*parameters here*/)
关于android - 分类器没有伴随对象,因此必须在这里初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53475759/