【发布时间】:2020-04-05 16:33:49
【问题描述】:
这是我父 xml 中的一些代码
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="(..).viewmodels.TestViewModel"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:theme="@style/AppTheme.AppBarOverlay"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent">
<include
android:id="@+id/layout"
bind:viewModel="@{viewModel}"
layout="@layout/test_content"/>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
这是子包含布局
<layout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="(..).TestViewModel" />
</data>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal"
tools:layout_editor_absoluteX="74dp"
tools:layout_editor_absoluteY="1dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/disable"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@color/orange"
android:text="@{viewModel.buttonText}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</layout>
正如您在此示例中所见,我将文本数据绑定到视图模型并通过 bind:viewModel="@{viewModel}" 将其从父级传递给子级
这是活动中的代码:
val binding:TestContentBinding = DataBindingUtil.setContentView(this, R.layout.test_content)
binding.setLifecycleOwner(this)
binding.viewModel = testViewModel
如果我将绑定设置为子 xml,则数据将被绑定,但是如果我将绑定设置为父活动,则视图模型不会被传递下去。
后端当然有正确的数据,但是我不知道如何将数据绑定到孩子。 我什至尝试过手动设置布局的 viewModel 但这不起作用。如何传递视图模型?
【问题讨论】:
-
可以改名试试吗?在包含布局中将此
bind:viewModel更改为bind:includeviewModel和在子布局中variable name ="includeviewModel" -
我试过了,没用
-
我这样做
app:viewModel="@{viewModel}"