簡體   English   中英

Android 當 viewModel 數據更改時,切換按鈕不會隨視圖綁定一起更新

[英]Android Toggle button doesn't update with view binding when viewModel data is changed

我覺得這是一件很簡單的事情,但我正在努力讓它在 Android 中工作。 我想要的只是讓我的切換按鈕的 state(打開或關閉)在 viewModel 更改時自動更新。 就在今天早上,我花了四個小時:) 我更新到 Android Studio 3.6 我在我的 gradle 文件中啟用了數據綁定。

dataBinding.enabled = true
viewBinding.enabled = true
dataBinding { enabled = true }
viewBinding {
    enabled = true
}

我在我的activity_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}"

在我的 viewModel 中,我嘗試過使用以下任何一種方法:

public final MutableLiveData<Boolean> checked = new MutableLiveData<>();
public boolean isChecked = true;

但無論我將 isChecked 或 check 的值設置為什么,toggleButton 都不會改變。 當我啟動應用程序時,它總是關閉。 我錯過了什么?

在綁定此視圖模型時,您應該在 MainActivity 中附加生命周期所有者。 它應該看起來像這樣

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM