Android 将不同的ViewModel传递到包含布局
我将包含一个传递viewmodel的布局:Android 将不同的ViewModel传递到包含布局,android,android-layout,android-databinding,Android,Android Layout,Android Databinding,我将包含一个传递viewmodel的布局: <include layout="@layout/user_login" app:model="@{model}" /> 我的目标是在通过不同ViewModel的不同位置使用此include 例如,我想在一个地方传递:UserViewModel,在另一个地方传递InformationViewModel。 我可以这样做吗 提前感谢这是组件类 class SomeComponent(context: Context, at
<include
layout="@layout/user_login"
app:model="@{model}" />
我的目标是在通过不同ViewModel的不同位置使用此include
例如,我想在一个地方传递: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}" />
谢谢您的回答。这里的目标是将不同的ViewModel传递给布局,例如:app:vm=“@{informationViewModel}”,或者我可以传递app:vm=“@{userViewModel}”@zerstoer,如果你想这样做,你需要创建“ParentVm”,在这里你可以放置两个vm。然后是“app:vm=“@{parent.user}”。这就是你要搜索的?我只想能够将一个视图模型传递给include布局。这样布局将获得它,并将单击功能从视图模型绑定到按钮onClick。但是视图模型不能总是相同的视图模型。