Android 安卓切换按钮没有';当viewModel数据更改时,不使用视图绑定进行更新

Android 安卓切换按钮没有';当viewModel数据更改时,不使用视图绑定进行更新,android,android-studio,android-layout,Android,Android Studio,Android Layout,我觉得这是一件很简单的事情,但我正在努力让它在Android中工作。我只希望切换按钮的状态(打开或关闭)在viewModel更改时自动更新。就在今天早上,我花了四个小时做这个:)我更新到了Android Studio 3.6,我的gradle文件中启用了数据绑定 dataBinding.enabled = true viewBinding.enabled = true dataBinding { enabled = true } viewBinding { enabled = true

我觉得这是一件很简单的事情,但我正在努力让它在Android中工作。我只希望切换按钮的状态(打开或关闭)在viewModel更改时自动更新。就在今天早上,我花了四个小时做这个:)我更新到了Android Studio 3.6,我的gradle文件中启用了数据绑定

dataBinding.enabled = true
viewBinding.enabled = true
dataBinding { enabled = true }
viewBinding {
    enabled = true
}
我在我的
activity\u main.xml
文件中添加了另一个布局标记:

    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">
        <data>
            <variable
                name="userModel"
                type="com.mycomp.myapp.UIViewModel"/>
        </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="0dp"
    >

Then for my toggle button I have:

     android:checked="@{userModel.isChecked}"

对于我的切换按钮,我有:
android:checked=“@{userModel.isChecked}”
在我的viewModel中,我尝试使用以下任一方法:

public final MutableLiveData<Boolean> checked = new MutableLiveData<>();
public boolean isChecked = true;
public final MutableLiveData checked=new MutableLiveData();
公共布尔值isChecked=true;

但无论我将isChecked或checked的值设置为什么,toggleButton都不会更改。当我启动应用程序时,它总是关闭。我缺少什么?

在主活动中,当绑定此viewModel时,应附加lifecycleOwner。应该是这样的

binding.setLifecycleOwner(getViewLifecycleOwner())
binding.userModel = userModel

谢谢,我不得不这样称呼它:binding.setUserModel(userModel);但这就是我丢失的那一块!