我包含了一个传递视图模型的布局:
<include
layout="@layout/user_login"
app:model="@{model}" />
我的目标是在不同的地方使用这个include,同时传递不同的ViewModel。
例如,我想在一个地方传递:UserViewModel,在另一个地方InformationViewModel。我能做到吗?
提前感谢
这是组件类
class SomeComponent(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {
private var mBinding: SomeLayoutBinding? = null
init {
if (isInEditMode) {
val view = LayoutInflater.from(context).inflate(R.layout.some_layout, this, false)
addView(view)
} else {
mBinding = SomeLayoutBinding.inflate(LayoutInflater.from(context), this, true)
}
}
fun setVm(vm: InformationViewModel) {
mBinding!!.vm = vm
mBinding!!.executePendingBindings()
}
}
以下是组件的布局
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="vm"
type="yourpackage.InformationViewModel" />
</data>
</layout>
以下是如何设置vm
<yourpackage.SomeComponent
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:vm="@{item}" />